私はerrorLogArrayList.length
が3であることを期待していますが、結果は2"forEach"のこの使用で何が問題になっていますか?
このコードは動作しない理由を私は期待して、それを修正する方法として、誰も私に教えてもらえますか?
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' ] ]
反復処理中の配列は変更しないでください。 – zerkms
@zerkmsそう、元の配列をクローンして残りの作業をするのですか? – hytm
@zenkms同時に2つの配列ではなく、1つの配列のみを変更すると、配列を変更することはできますか? – hytm