如何创建要添加到JavaScript对象变量的动态密钥 [英] How do I create a dynamic key to be added to a JavaScript object variable

查看:88
本文介绍了如何创建要添加到JavaScript对象变量的动态密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

方括号:

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

在JavaScript中,所有数组都是对象,但并非所有对象都是数组。主要区别(以及非常难以模仿直接JavaScript和普通对象的那个)是数组实例维护长度属性,以便它反映一个加上数字的值名称为numeric的属性,其值在转换为数字时是所有此类属性中最大的。这听起来很奇怪,但它只是意味着给定一个数组实例,名称如05207,等等,都是专门处理的,因为它们的存在决定了长度。而且,除此之外, length 的值可以设置删除这样的属性。将数组的 length 设置为 0 可以有效地删除名称看起来像整数的所有属性。

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对象属性名称可以是您喜欢的任何类型的字符串。

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.

因此,<$ c $的方式c> [] 运算符在中用于循环迭代数组:

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

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 precisely the same thing in both instances. The fact that in one case the object involved happens to be an array is unimportant, in other words.

使用<$ 设置属性值时c $ c> [] ,关于维护 length 属性的特殊行为,故事与相同。如果在数组实例上使用数字键设置属性:

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

myArray[200] = 5;

然后(假设200是最大的数字属性名称)长度属性将更新为 201 作为属性赋值的副作用。但是,如果对普通对象做了同样的事情:

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

myObj[200] = 5;

没有这样的副作用。数组和对象的名为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 5 in otherwise the exact same way.

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

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的值将是一个只包含的字符串[你好世界] ; 某物属性将会丢失。

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

如果你能够使用ES6 JavaScript功能,您可以使用计算属性名称非常容易处理:

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

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

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

这篇关于如何创建要添加到JavaScript对象变量的动态密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆