在Javascript中的嵌套数组的浅副本上迭代



我有一个嵌套数组:

let array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];

我需要迭代每个嵌套数组的第一个和第二个元素,并更新原始数组上的更改。我该如何做到这一点?我尝试了很多选项,但结果不会更新原始数组。例如:

let arrayCop = [];
for (let i = 0; i <= 1; i++) {
for (let j = 0; j <= 1; j++) {
arrayCop.push(array[i][j]);
}
}
arrayCop.forEach(...);

谢谢。

这是我的完整代码,我正在尝试构建一个合法的数独生成器:

let sudoku = [];
function populateSudoku() {
let array = [];
while (array.length <= 8) {
let randomNum = Math.floor(Math.random() * 9 + 1);
array.push(randomNum);
if (array.indexOf(randomNum) < array.lastIndexOf(randomNum)) {
array.pop()
}
}
return array;
}
while (sudoku.length <= 8) {
sudoku.push(populateSudoku());
}
for (let i = 0; i < sudoku.length; i++) {
for (let j = 0; j < sudoku.length; j++) {
sudoku[i].forEach(element => {
if (sudoku[i].indexOf(element) === sudoku[j].indexOf(element) &&
(i !== j)) {
sudoku[j][sudoku[i].indexOf(element)] = 0;
}
})
}
}
let array = [];
for (let i = 0; i <= 2; i++) {
for (let j = 0; j <= 2; j++) {
array.push(sudoku[i][j]);
}
}
array[3] = 452345;
console.log(sudoku);

**

#我做到了#

**

let array = [[1, 2, 3], [7, 4, 1], [2, 4, 3]];
// checks for duplicates just in first and second item of every file
for (let i = 0; i <= 1; i++) {
for (let j = 0; j <= 2; j++) {
array[i].forEach((element, index) => {
if ((i !== j) && index <= 1 &&
(array[j].indexOf(element) >= 0 && array[j].indexOf(element) <= 1)) {
array[i][index] = 'x';
}
})
}
}
console.log(array);

如果我理解正确,您想将原始数组更改为:

[[1, 2], [4, 5], [7, 8]]

如果是这样的话,这就可以了:

array.forEach(element => element.splice(2))

您可以使用Array.prototype.map函数

ORIGINAL

我需要迭代每个嵌套的第一个和第二个元素阵列并更新原始阵列上的更改

function iterate(array) {
array.forEach(function(element, index) {
console.log('[' + index + "][0]", element[0]);
console.log('[' + index + "][1]", element[1])
})
}

不过,不确定更新对原始数组的更改是什么意思。。。

编辑

好吧,在看了其他答案之后,我相信@NinaW得到了你想要的。

function parse(array) {
array.forEach(function(element) { element.slice(0, 2) })
}

使用flatMap和析构函数。

let array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
let arrayCop = array.flatMap(([first, second]) => [first, second]);
console.log(arrayCop)

let array = [[1, 2, 3], [7, 4, 1], [2, 4, 3]];
console.log(array);
// checks for duplicates just in first and second item of every file
for (let i = 0; i <= 1; i++) {
for (let j = 0; j <= 2; j++) {
array[i].forEach((element, index) => {
if ((i !== j) && index <= 1 &&
(array[j].indexOf(element) >= 0 && array[j].indexOf(element) <= 1)) {
array[i][index] = 'x';
}
})
}
}
console.log(array);

最新更新