如何创建要添加到 JavaScript 对象变量的动态键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2462800/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:28:41  来源:igfitidea点击:

How do I create a dynamic key to be added to a JavaScript object variable

javascriptobject

提问by Ryan

I'm trying something like this, but this example does not work.

我正在尝试这样的事情,但这个例子不起作用。

jsObj = {};

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

What can I do to make a dynamic key like this?

我该怎么做才能制作这样的动态密钥?

回答by Pointy

Square brackets:

方括号:

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 lengthproperty 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 lengthcan be setto removesuch properties. Setting the lengthof an array to 0effectively removes all properties whose names look like whole numbers.

在 JavaScript 中,所有数组都是对象,但并非所有对象都是数组。主要区别(并且很难用直接的 JavaScript 和普通对象模仿)是数组实例维护length属性,以便它反映名称为数字的属性的数字值,当转换为数字时,它的值, 是所有此类属性中最大的。这听起来很奇怪,但这只是意味着给定一个数组实例,名称如"0""5"、等的属性"207"都被特殊对待,因为它们的存在决定了 的值length。而且,最重要的是,length可以设置的值以删除此类属性。将length数组的设置为0有效地删除名称看起来像整数的所有属性。

OK, so that's what makes an array special. All of that, however, has nothing at all to do with how the JavaScript [ ]operator works. That operator is an object property access mechanism which works on any object. It's important to note in that regard that numeric array property names are not special as far as simple property access goes. They're just strings that happen to look like numbers, but JavaScript object property names can be any sort of string you like.

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

Thus, the way the [ ]operator works in a forloop iterating through an array:

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

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

is really no different from the way [ ]works when accessing a property whose name is some computed string:

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

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

The [ ]operator there is doing preciselythe same thing in both instances. The fact that in one case the object involved happens to be an array is unimportant, in other words.

在这两种情况下,[ ]那里的操作员都在做完全相同的事情。换句话说,在一种情况下,所涉及的对象恰好是一个数组这一事实并不重要。

When settingproperty values using [ ], the story is the same exceptfor the special behavior around maintaining the lengthproperty. If you set a property with a numeric key on an array instance:

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

myArray[200] = 5;

then (assuming that "200" is the biggest numeric property name) the lengthproperty will be updated to 201as a side-effect of the property assignment. If the same thing is done to a plain object, however:

然后(假设“200”是最大的数字属性名称)该length属性将被更新201为属性分配的副作用。但是,如果对普通对象执行相同的操作:

myObj[200] = 5;

there's no such side-effect. The property called "200" of both the array and the object will be set to the value 5in otherwise the exact same way.

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

One might think that because that lengthbehavior is kind-of handy, you might as well make allobjects 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 lengthbut 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 onlyinvolves the numerically-named properties. Other properties added to the array will never appear in the serialized JSON form. So for example:

有人可能会认为,因为这种length行为有点方便,所以您最好将所有对象作为 Array 构造函数的实例而不是普通对象。这并没有什么直接的错误(尽管它可能会令人困惑,尤其是对于熟悉某些其他语言的人,某些属性包含在其中length但不包含在其他语言中)。但是,如果您正在使用 JSON 序列化(相当常见的事情),请了解数组实例以涉及数字命名属性的方式序列化为 JSON 。添加到数组的其他属性永远不会出现在序列化的 JSON 形式中。例如:

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

var objJSON = JSON.stringify(obj);

the value of "objJSON" will be a string containing just ["hello world"]; the "something" property will be lost.

“objJSON”的值将是一个只包含["hello world"]; “某物”财产将丢失。

ES2015:

ES2015:

If you're able to use ES6 JavaScript features, you can use Computed Property Namesto handle this very easily:

如果您能够使用 ES6 JavaScript 功能,您可以使用计算属性名称来非常轻松地处理此问题:

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

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

回答by Andy E

Associative Arrays in JavaScript don't really work the same as they do in other languages. for eachstatements are complicated (because they enumerate inherited prototype properties). You could declare properties on an object/associative array as Pointy mentioned, but really for this sort of thing you should use an array with the pushmethod:

JavaScript 中的关联数组的工作方式与其他语言中的不同。 for each语句很复杂(因为它们枚举继承的原型属性)。您可以像 Pointy 提到的那样在对象/关联数组上声明属性,但实际上对于这种事情,您应该将数组与push方法一起使用:

jsArr = []; 

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

Just don't forget that indexed arrays are zero-based so the first element will be jsArr[0], not jsArr[1].

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