我正在使用这样的函数填充我的数组:
const items = [
{name : 'original', count: 'one'},
{name: 'copy', count: 'two'},
{name: 'redundant', count: 'three'}];
let myitems = [];
items.forEach(function (k) {
myitems[k.name] = myFunction(k.count);
}, this);
console.log('final nurls: ', myitems);
在执行console.log返回空!
但是当我这样做时:
items.forEach(function (k) {
let item = myFunction(k.count)
myitems.push(item);
}, this);
然后控制台日志返回预期的结果。
为什么第一个版本返回空?
当您将“myitems”定义为数组时,它不能包含键值对。
myitems[k.name] = X;想这样做,而
myitems.push(X);正在向数组添加新项目。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句