我希望errorLogArrayList.length
为3,但结果是2。
有人可以告诉我为什么这段代码不能正常运作以及如何修复它?
CODE:
var logArrayList = [
[1,2,3],
[1,2,"error"],
[1,2,"error"],
[1,2,"error"]
]
var errorLogArrayList = [];
console.log(logArrayList);
console.log("======================");
logArrayList.forEach(function(logArray, index, self) {
if(logArray[2] === "error") {
var errorArray = self.splice(index, 1)[0];
errorLogArrayList.push(errorArray);
}
});
// I expect this value to be 3, but the result is 2.
console.log("errorLogArrayList.length is " + errorLogArrayList.length)
console.log(errorLogArrayList);
console.log("======================");
// I expect this value to be 1, but the result is 2.
console.log("logArrayList.length is " + logArrayList.length);
console.log(logArrayList);
LOG:
[ [ 1, 2, 3 ],
[ 1, 2, 'error' ],
[ 1, 2, 'error' ],
[ 1, 2, 'error' ] ]
======================
// I expect this value to be 3, but the result is 2.
errorLogArrayList.length is 2
[ [ 1, 2, 'error' ], [ 1, 2, 'error' ] ]
======================
//I expect this value to be 1, but the result is 2.
logArrayList.length is 2
[ [ 1, 2, 3 ], [ 1, 2, 'error' ] ]
答案 0 :(得分:2)
您可以执行filter
操作:
var errorLogArrayList = logArrayList.filter(function(array) {
return array[2] === 'error';
});
logArrayList = logArrayList.filter(function(array) {
return array[2] !== 'error';
});
不幸的是,这需要一些重复的迭代。如果您愿意,可以使用_.partition from lodash(看起来更清洁):
var lists = _.partition(logArrayList, function(array) {
return array[2] === 'error';
});
var errorLogArrayList = lists[0];
logArrayList = lists[1];
您当前的方法存在的问题是您正在尝试跟踪多个状态并同时修改两个数组,这会导致一些数据冲突。 filter
通常更具说明性,它不会改变原始数组,而是返回一个新数组。
希望在评论中添加@zerkms建议的reduce
方法:
var lists = logArrayList.reduce(function(agg, curr) {
if(curr[2] === 'error') {
agg[0] = (agg[0] || []).concat([curr]);
} else {
agg[1] = (agg[1] || []).concat([curr]);
}
return agg;
}, []);
与partition
示例相同。