小编典典

重新分配变量值导致数组内出现问题(vanilla JavaScript)

javascript

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

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

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

然而,结果数组是这样的: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}`);

阅读 114

收藏
2022-07-27

共1个答案

小编典典

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

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
}))
2022-07-27