我正在尝试.reduce()
,在下面的测试代码中,我尝试将accumulator.key[index]
设置为值1。通过使用console.log
,我可以看到索引从0到3正确循环。但是,我的代码仅将accumulator.key[3]
设置为值1。它以未定义为单位的第一个3 accumulator.key[index]
。这对我来说完全令人困惑。我看不出为什么它不会将所有4个键设置为1。感谢您的任何帮助!
"use strict";
var testArray = ['fe', 'fi', 'fo', 'fum'];
var output;
output = testArray.reduce((accumulator, currentValue, index) => {
accumulator.key = [];
console.log(index);
accumulator.key[index] = 1;
return accumulator;
}, []);
console.log(output.key);
您在每次迭代中使用此语句accumulator.key = []
分配给key
属性的新 []
,该属性将删除先前的数组参考。将对象转换为一个数组,然后将其定义为 key
属性为数组。
var testArray = ['fe', 'fi', 'fo', 'fum'];
var output;
output = testArray.reduce((accumulator, currentValue, index) => {
console.log(index);
accumulator.key[index] = 1;
return accumulator;
}, { key: [] });
console.log(output.key);
我不确定您的用例在数组上使用.key
,但是如果您决定的是,那就不要将其初始化为每次迭代的数组。而且,如果您害怕在第一次迭代中获得不确定的,请使用后式空排数组。
accumulator.key = (accumulator.key || []);
"use strict";
var testArray = ['fe', 'fi', 'fo', 'fum'];
var output;
output = testArray.reduce((accumulator, currentValue, index) => {
accumulator.key = (accumulator.key || []);
console.log(index);
accumulator.key[index] = 1;
return accumulator;
}, []);
console.log(output.key);