简体   繁体   English

使用forEach迭代数组,添加到对象并为对象键使用forEach索引不起作用

[英]Using forEach to iterate an array, add to object and use the forEach index for the object key doesn't work

I'm wanting to iterate of an array using forEach , then add the values of that array to an object. 我想使用forEach迭代数组,然后将该数组的值添加到对象。

When adding to the object I want to be able to name the object keys with an increasing number, just like when using a normal for loop using the i variable counter. 当添加到对象中时,我希望能够使用递增的数字来命名对象键,就像使用i变量计数器使用普通的for loop时一样。

With the code below: 使用以下代码:

var myArray = [123, 15, 187, 32];
var testObj = {}
myArray.forEach(function (value, i) {
    console.log('%d: %s', i, value);
    var objectKeyName = "item" + i; // ⬅️ here
    testObj.objectKeyName = value;
});
console.log(testObj);

I would expect testObj to be 我希望testObj

{
    item0: 123,
    item1: 15,
    item2: 187,
    item3: 32, 
}

instead it outputs: 相反,它输出:

{objectKeyName: 32}

Why is this? 为什么是这样? Any help is greatly appreciated! 任何帮助是极大的赞赏! 😀 😀

The issue is because you're using a variable as the property name. 问题是因为您使用变量作为属性名称。 In that situation you cannot use dot notation, and must instead use bracket notation to access the object. 在这种情况下,您不能使用点表示法,而必须使用括号表示法来访问对象。

The reason you see only one item in the object currently is because you only set the objectKeyName property, and overwrite it in each iteration of the forEach . 当前仅在对象中看到一项的原因是,您仅设置了objectKeyName属性,并在forEach每次迭代中将其覆盖。

 var myArray = [123, 15, 187, 32]; var testObj = {} myArray.forEach(function(value, i) { var objectKeyName = "item" + i; testObj[objectKeyName] = value; // Note the [] surrounding the variable name here }); console.log(testObj); 

Use testObj[objectKeyName] = value instead of testObj.objectKeyName = value . 使用testObj[objectKeyName] = value代替testObj.objectKeyName = value The dot notation assigns the key value literally. 点表示法从字面上分配键值。

Here you go with the solution 解决方案在这里

 var myArray = [123, 15, 187, 32]; var testObj = {} myArray.forEach(function(value, i) { testObj["item" + i] = value; }); console.log(testObj); 

var myArray = [123, 15, 187, 32];
var testObj = [];
myArray.forEach(function (value, i) {
    console.log('%d: %s', i, value);
    var objectKeyName = "item" + i; // ⬅️ here
    testObj.push(objectKeyName + ":" + value);
});
console.log(testObj);
testObj.forEach(function (value, i) {
    console.log(value);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM