变量值的重新分配导致数组中出现问题(普通JavaScript)



上下文:我正在编写的程序生成一个包含数组的数组。我想根据arrayElement[0]的值(即每个子数组中的第一个值(对数组进行排序。

在下面的示例中,我取arrayElement[0]值,将它们放入一个单独的数组(tempSortArray(中并对它们进行排序。然后,我运行一个嵌套循环,从原始foo数组中获取项目,并将它们按顺序放入finalFooArray中。

实际问题:如果有多个数组项具有相同的arrayElement[0]值,我在将y添加到finalFooArray之后添加了y[0] = false。这应该可以防止代码不断地添加相同的元素。

然而,得到的数组是这样的:false,[object Object],[object Object],false,[object Object],[object Object],false,[object Object],[object Object],即y[0] = false以某种方式进入数组,尽管我在将值放入数组后更改了值

有人能解释为什么会发生这种情况,以及我如何防止这种情况发生吗?

var foo = [
[28888888, {x: 12,y: 3},{x: 1,y: 45678}],
[78, {x: 54,y: 3}, {x: 3,y: 3}],
[456, {x: 1,y: 76543}, {x: 765432,y: 7}]
];
let tempSortArray = [];
let finalFooArray = [];
foo.forEach((item) => {
tempSortArray.push(item[0]);
});
tempSortArray.sort(function(a, b) {
return a - b
});

for (let x of tempSortArray) {
for (let y of foo) {
if (x == y[0]) {
finalFooArray.push(y);
y[0] = false; // Change the value of y[0] just in case there are several items with the same y[0] value
}
}
}
console.log(`The sorted array goes like this: ${finalFooArray}`);

为什么不按每个数组的第一项排序?

var foo = [
[28888888, {x: 12,y: 3},{x: 1,y: 45678}],
[78, {x: 54,y: 3}, {x: 3,y: 3}],
[456, {x: 1,y: 76543}, {x: 765432,y: 7}]
];

console.log(foo.sort(function(a, b) {
if (a[0] > b[0]) return 1;
if (a[0] < b[0]) return -1;
return 0
}))

您不需要临时数组;只需直接对数组进行排序,返回回调中第一个元素之间的差异。

var foo = [
[28888888, {x: 12,y: 3},{x: 1,y: 45678}],
[78, {x: 54,y: 3}, {x: 3,y: 3}],
[456, {x: 1,y: 76543}, {x: 765432,y: 7}]
];
foo.sort((a, b)=>a[0] - b[0]);
console.log(JSON.stringify(foo));

最新更新