本文介绍了如何在JavaScript中正确地将对象从for循环推送到数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个包含for循环但是有问题的数组,我想要的形状如下:

I want to make an array that including object by for loop but there is a problem, The shape what I want is below :

[
  { data: 'apple', label: 'Fruits'  },
  { data: 'banana', label: 'Fruits' },
  { data: 'mango', label: 'Fruits'  }
]

所以我尝试了以下方式,但它是不能正常工作。

So I tried to below way, but It's not working properly.

var arr = [];
obj = {};
var fruits = ['banana', 'apple', 'mango'];
var label = 'Fruits';

for (var i=0; i<fruits.length; i++){
    obj['data'] = fruits[i];
    obj['label'] = label;
    arr.push(obj);
}

console.log(arr);

结果就是推送同一个对象。

The result is just same object pushed.

[
  { data: 'apple', label: 'Fruits' },
  { data: 'apple', label: 'Fruits' },
  { data: 'apple', label: 'Fruits' }
]

Is这是因为功能更近?我怎样才能做得好?

Is this because of closer function ? How can I make it well?

推荐答案

这种情况正在发生,因为 obj 对象正在引用同一个对象并在每次迭代中更新。

That's happening because the obj object is referencing to the same object and it is updated in each iteration.

在循环内引用相同的对象 obj

The same object obj is referenced inside the loop

在循环中移动对象声明以在每次迭代中创建一个新对象。

Move the object declaration inside the loop to create a new object in each iteration.

for(var i = 0; i < fruits.length; i++) {
    var obj = {}; // <---- Move declaration inside loop

    obj['data'] = fruits[i];
    obj['label'] = label;
    arr.push(obj);
}
var arr = [];
var fruits = ['banana', 'apple', 'mango'];
var label = 'Fruits';

for(var i = 0; i < fruits.length; i++) {
    var obj = {};
    obj['data'] = fruits[i];
    obj['label'] = label;
    arr.push(obj);
}

console.log(arr);

避免这种情况的一种简单方法是使用从旧创建新数组。

A simple way to avoid this is using Array#map to create new array from old.

var arr = fruits.map(fruit => ({
    data: fruit,
    label: label
}));
var arr = [],
    fruits = ['banana', 'apple', 'mango'],
    label = 'Fruits';

var arr = fruits.map(fruit => ({
    data: fruit,
    label: label
}));
console.log(arr);

这篇关于如何在JavaScript中正确地将对象从for循环推送到数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-29 05:59
查看更多