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

查看:25
本文介绍了如何创建要添加到 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 和普通对象模仿)是数组实例维护 length 属性,以便它反映名称为 numeric 和当转换为数字时,其值是所有此类属性中最大的.这听起来真的很奇怪,但这只是意味着给定一个数组实例,属性名称为 "0", "5", "207"; 等都被特殊对待,因为它们的存在决定了length 的值.并且,最重要的是,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.

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

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.

当使用[ ]设置属性值时,故事是相同的除了围绕保持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"是最大的数字属性名称)作为属性分配的副作用,length 属性将更新为 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 构造函数的 all 对象实例,而不是普通对象.这并没有什么直接的错误(尽管它可能会令人困惑,特别是对于熟悉某些其他语言的人来说,某些属性包含在 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"的值将是一个只包含 ["hello world"] 的字符串;某物"财产会丢失.

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天全站免登陆