我正在尝试类似的东西,但这个例子不起作用。

jsObj = {};

for (var i = 1; i <= 10; i++) {
    jsObj{'key' + i} = 'example ' + 1;
}

我怎么做一个这样的动态键呢?


方括号:

jsObj['key' + i] = 'example' + 1;

In JavaScript, all arrays are objects, but not all objects are arrays. The primary difference (and one that's pretty hard to mimic with straight JavaScript and plain objects) is that array instances maintain the length property so that it reflects one plus the numeric value of the property whose name is numeric and whose value, when converted to a number, is the largest of all such properties. That sounds really weird, but it just means that given an array instance, the properties with names like "0", "5", "207", and so on, are all treated specially in that their existence determines the value of length. And, on top of that, the value of length can be set to remove such properties. Setting the length of an array to 0 effectively removes all properties whose names look like whole numbers.

这就是数组的特殊之处。然而,所有这些都与JavaScript[]操作符的工作方式毫无关系。该操作符是一种对象属性访问机制,适用于任何对象。在这方面需要注意的是,就简单的属性访问而言,数值数组属性名并不特殊。它们只是碰巧看起来像数字的字符串,但JavaScript对象属性名可以是任何类型的字符串。

因此,[]操作符在for循环中遍历数组的方式是:

for (var i = 0; i < myArray.length; ++i) {
  var value = myArray[i]; // property access
  // ...
}

实际上与[]在访问名称为某个计算字符串的属性时的工作方式没有什么不同:

var value = jsObj["key" + i];

[]运算符在两个实例中做的事情完全相同。换句话说,在一种情况下,所涉及的对象恰好是一个数组,这一点并不重要。

当使用[]设置属性值时,除了维护length属性的特殊行为外,情况是相同的。如果你在数组实例上用数字键设置属性:

myArray[200] = 5;

然后(假设“200”是最大的数字属性名)length属性将作为属性赋值的副作用被更新为201。然而,如果对普通对象做同样的事情,则:

myObj[200] = 5;

没有这样的副作用。数组和对象的名为“200”的属性将以完全相同的方式被设置为值5。

One might think that because that length behavior is kind-of handy, you might as well make all objects instances of the Array constructor instead of plain objects. There's nothing directly wrong about that (though it can be confusing, especially for people familiar with some other languages, for some properties to be included in the length but not others). However, if you're working with JSON serialization (a fairly common thing), understand that array instances are serialized to JSON in a way that only involves the numerically-named properties. Other properties added to the array will never appear in the serialized JSON form. So for example:

var obj = [];
obj[0] = "hello world";
obj["something"] = 5000;

var objJSON = JSON.stringify(obj);

"objJSON"的值将是一个字符串,只包含["hello world"];“某些”属性将会丢失。

ES2015:

如果你能够使用ES6 JavaScript特性,你可以使用计算属性名称来很容易地处理这个问题:

var key = 'DYNAMIC_KEY',
    obj = {
        [key]: 'ES6!'
    };

console.log(obj);
// > { 'DYNAMIC_KEY': 'ES6!' }

JavaScript中的关联数组与其他语言中的关联数组的工作原理并不相同。因为每个语句都很复杂(因为它们列举了继承的原型属性)。你可以像Pointy提到的那样在一个对象/关联数组上声明属性,但对于这种事情,你应该使用一个带有push方法的数组:

jsArr = []; 

for (var i = 1; i <= 10; i++) { 
    jsArr.push('example ' + 1); 
} 

不要忘记,索引数组是从零开始的,所以第一个元素将是jsArr[0],而不是jsArr[1]。