到目前为止,我找到的所有文档都是更新已经创建的键:

 arr['key'] = val;

我有一个这样的字符串:" name = oscar "

我想以这样的方式结束:

{ name: 'whatever' }

也就是说,分割字符串并获得第一个元素,然后将其放入字典中。

Code

var text = ' name = oscar '
var dict = new Array();
var keyValuePair = text.split(' = ');
dict[ keyValuePair[0] ] = 'whatever';
alert( dict ); // Prints nothing.

使用第一个例子。如果该键不存在,它将被添加。

var a = new Array();
a['name'] = 'oscar';
alert(a['name']);

将弹出一个包含'oscar'的消息框。

Try:

var text = 'name = oscar'
var dict = new Array()
var keyValuePair = text.replace(/ /g,'').split('=');
dict[ keyValuePair[0] ] = keyValuePair[1];
alert( dict[keyValuePair[0]] );

为了响应MK_Dev,可以进行迭代,但不是连续的(显然,需要一个数组)。

快速搜索谷歌会出现JavaScript哈希表。

在哈希中遍历值的示例代码(来自上述链接):

var myArray = new Array();
myArray['one'] = 1;
myArray['two'] = 2;
myArray['three'] = 3;

// Show the values stored
for (var i in myArray) {
    alert('key is: ' + i + ', value is: ' + myArray[i]);
}

JavaScript没有关联数组。它有对象。

下面几行代码都做了完全相同的事情——将对象上的'name'字段设置为'orion'。

var f = new Object(); f.name = 'orion';
var f = new Object(); f['name'] = 'orion';
var f = new Array(); f.name = 'orion';
var f = new Array(); f['name'] = 'orion';
var f = new XMLHttpRequest(); f['name'] = 'orion';

它看起来像你有一个关联数组,因为数组也是一个对象-然而你实际上并没有向数组中添加东西;你在对象上设置字段。

现在已经解决了这个问题,下面是你的例子的一个工作解决方案:

var text = '{ name = oscar }'
var dict = new Object();

// Remove {} and spaces
var cleaned = text.replace(/[{} ]/g, '');

// Split into key and value
var kvp = cleaned.split('=');

// Put in the object
dict[ kvp[0] ] = kvp[1];
alert( dict.name ); // Prints oscar.

从某种程度上说,所有的例子虽然都很好,但都过于复杂了:

他们使用new Array(),这对于简单的关联数组(又名字典)来说是一种过度(和开销)。 较好的使用new Object()。它工作得很好,但是为什么要进行这些额外的输入呢?

这个问题被标记为“初学者”,所以让我们把它简化。

在JavaScript中使用字典的über-simple方法或“为什么JavaScript没有一个特殊的字典对象?”:

// Create an empty associative array (in JavaScript it is called ... Object)
var dict = {};   // Huh? {} is a shortcut for "new Object()"

// Add a key named fred with value 42
dict.fred = 42;  // We can do that because "fred" is a constant
                 // and conforms to id rules

// Add a key named 2bob2 with value "twins!"
dict["2bob2"] = "twins!";  // We use the subscript notation because
                           // the key is arbitrary (not id)

// Add an arbitrary dynamic key with a dynamic value
var key = ..., // Insanely complex calculations for the key
    val = ...; // Insanely complex calculations for the value
dict[key] = val;

// Read value of "fred"
val = dict.fred;

// Read value of 2bob2
val = dict["2bob2"];

// Read value of our cool secret key
val = dict[key];

现在让我们改变值:

// Change the value of fred
dict.fred = "astra";
// The assignment creates and/or replaces key-value pairs

// Change the value of 2bob2
dict["2bob2"] = [1, 2, 3];  // Any legal value can be used

// Change value of our secret key
dict[key] = undefined;
// Contrary to popular beliefs, assigning "undefined" does not remove the key

// Go over all keys and values in our dictionary
for (key in dict) {
  // A for-in loop goes over all properties, including inherited properties
  // Let's use only our own properties
  if (dict.hasOwnProperty(key)) {
    console.log("key = " + key + ", value = " + dict[key]);
  }
}

删除值也很简单:

// Let's delete fred
delete dict.fred;
// fred is removed, but the rest is still intact

// Let's delete 2bob2
delete dict["2bob2"];

// Let's delete our secret key
delete dict[key];

// Now dict is empty

// Let's replace it, recreating all original data
dict = {
  fred:    42,
  "2bob2": "twins!"
  // We can't add the original secret key because it was dynamic, but
  // we can only add static keys
  // ...
  // oh well
  temp1:   val
};
// Let's rename temp1 into our secret key:
if (key != "temp1") {
  dict[key] = dict.temp1; // Copy the value
  delete dict.temp1;      // Kill the old key
} else {
  // Do nothing; we are good ;-)
}

原始代码(我添加了行号,以便可以引用它们):

1  var text = ' name = oscar '
2  var dict = new Array();
3  var keyValuePair = text.split(' = ');
4  dict[ keyValuePair[0] ] = 'whatever';
5  alert( dict ); // Prints nothing.

差不多了…

第1行:你应该在文本上做一个修剪,所以它是name = oscar。 行3:只要等号周围有空格就行。 在第1行中不修剪可能会更好。使用=并修剪每个keyValuePair 在3和4之前加一行: key = keyValuePair[0]; ' 第4行:现在变成: dict[key] = keyValuePair[1]; 第5行:更改为: Alert (dict['name']);//输出'oscar'

我试图说字典[keyValuePair[0]]不工作。您需要设置一个字符串keyValuePair[0],并使用它作为关联键。这是唯一能让我的工作顺利进行的方法。设置完成后,可以使用数字索引或引号中的键来引用它。


var myArray = new Array();
myArray['one'] = 1;
myArray['two'] = 2;
myArray['three'] = 3;

// Show the values stored
for (var i in myArray) {
    alert('key is: ' + i + ', value is: ' + myArray[i]);
}

这是可以的,但是它遍历数组对象的每个属性。

如果你只想遍历myArray属性。1、myArray.two……你可以这样尝试:

myArray['one'] = 1;
myArray['two'] = 2;
myArray['three'] = 3;
myArray.push("one");
myArray.push("two");
myArray.push("three");
for(var i=0;i<maArray.length;i++){
    console.log(myArray[myArray[i]])
}

现在您可以通过myArray["one"]访问这两个属性,并且只遍历这些属性。


所有现代浏览器都支持Map,这是一个键/值数据结构。有几个原因使得使用Map比使用Object更好:

Object有一个原型,所以映射中有默认键。 Object的键是字符串,它们可以是Map的任何值。 当你必须跟踪对象的大小时,你可以很容易地获得Map的大小。

例子:

var myMap = new Map();

var keyObj = {},
    keyFunc = function () {},
    keyString = "a string";

myMap.set(keyString, "value associated with 'a string'");
myMap.set(keyObj, "value associated with keyObj");
myMap.set(keyFunc, "value associated with keyFunc");

myMap.size; // 3

myMap.get(keyString);    // "value associated with 'a string'"
myMap.get(keyObj);       // "value associated with keyObj"
myMap.get(keyFunc);      // "value associated with keyFunc"

如果希望垃圾收集没有从其他对象引用的键,可以考虑使用WeakMap而不是Map。


我认为如果你像这样创建它会更好:

var arr = [];

arr = {
   key1: 'value1',
   key2:'value2'
};

想了解更多信息,看看这个:

JavaScript数据结构-关联数组


var obj = {};

for (i = 0; i < data.length; i++) {
    if(i%2==0) {
        var left = data[i].substring(data[i].indexOf('.') + 1);
        var right = data[i + 1].substring(data[i + 1].indexOf('.') + 1);

        obj[left] = right;
        count++;
    }
}

console.log("obj");
console.log(obj);

// Show the values stored
for (var i in obj) {
    console.log('key is: ' + i + ', value is: ' + obj[i]);
}


}
};
}

const阵列= [ “yPnPQpdVgzvSFdxRoyiwMxcx”, “yPnPQpdVgzvSFdxRoyiwMxcx”, “a96b3Z-rqt6U3QV_1032fxcsa”, “iNeoJfVnF7dXqARwnDOhj233dsd” ]; 地图(x)=> 归来{ _id: x 的 }); 控制台日志(newArr)。