我从一个数组中切出 3 个元素并将它们存储到另一个数组中
array = [1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1];
rows = 3;
这是我的方法
getVertWallStruct = (array, rows) => {
let i = 1,
storageArr = [],
data = [];
for (let k = 0; k < rows*2; k++) { // everything's ok here
storageArr.push(array.slice(k*rows, (k+1)*rows));
}
data = storageArr;
console.log("storageArr - ", storageArr, " , array - ", array, " , data - ", data);
return data;
}
在这种情况下,storageArr 将包含空数组(就数据而言)。但是当我用 data = storageArr; 删除行时,我得到:
storageArr = [ //storageArr should look like this in the end
[1, 1, 1],
[0, 1, 1],
[1, 1, 1],
[1, 1, 1],
[0, 1, 1],
[1, 1, 1]
]
为什么我会失去值(value)观?
更新: 即使我从其中一个答案中复制粘贴代码 - 方法也会返回空数据。为什么?
代码如下:
getVertWallStruct = (array, rows) => {
console.log(array, rows); //okay here
let iterator = array.values()
let out = []
for (let i = 0;i < ~~(array.length / rows); i++){
out.push([iterator.next().value, iterator.next().value, iterator.next().value])
}
console.log(out); //empty ???
return out;
}
最佳答案
一种可能的方法是使用数组迭代器:
The values() method returns a new Array Iterator object that contains the values for each index in the array. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values
const array = [1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1]
let iterator = array.values()
let out = []
for (let i = 0;i < ~~(array.length / 3);i++){
out.push([iterator.next().value, iterator.next().value, iterator.next().value])
}
console.log(out)
更新,这看起来工作正常:
Update: Even when I copy-pasted code from one of the answers - method returns empty data. Why?
getVertWallStruct = (array, rows) => {
let iterator = array.values()
let out = []
for (let i = 0;i < ~~(array.length / rows); i++){
out.push([iterator.next().value, iterator.next().value, iterator.next().value])
}
return out;
};
console.log(
getVertWallStruct([1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1], 3)
)
关于javascript - 从数组中丢失数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62648097/