【问题标题】:Why is splicing an array in JavaScript removing the last few elements?为什么在 JavaScript 中拼接数组会删除最后几个元素?
【发布时间】:2021-08-15 18:24:23
【问题描述】:

我目前正在研究一个数组函数,它将连续数字的子数组转换为表示该数字范围的字符串——例如,这个数组...

[1, 2, 3, 6, 8, 10, 11, 12, 15, 18]

...会变成这个数组:

["1-3", 6, 8, "10-12", 15, 18]

我已经能够开发出一个大部分可以工作的函数,但是我遇到了一个奇怪的错误,其中所有超出拼接到数组中的最终数字范围的元素都被完全删除了。比如上面的测试数组其实变成了这样:

["1-3", 6, 8, "10-12"]

这是我到目前为止编写的代码。它还不是很漂亮,但正如我上面提到的,它可以一直到最后完成工作:

let testArray = [1, 2, 3, 6, 8, 10, 11, 12, 15, 18];

for (i = 0; i < testArray.length; i++) {
  let consecutives = [];
  consecutives.push(testArray[i]);
  let j = i + 1;
  while (j < testArray.length) {
    if (testArray[j] == (testArray[j - 1] + 1)) {
      consecutives.push(testArray[j]);
      j++;
    } else {
      break;
    }
  }
  if (consecutives.length > 2) {
    let range = String(testArray[i]) + "-" + String(testArray[j - 1]);
    console.log(testArray);
    console.log(testArray[i]);
    console.log(testArray[j]);
    testArray.splice(i, j, range);
  }
}

console.log(testArray);

这些是该代码输出的控制台日志:

Array(10) [ 1, 2, 3, 6, 8, 10, 11, 12, 15, 18 ]
1
6
Array(8) [ "1-3", 6, 8, 10, 11, 12, 15, 18 ]
10
15
Array(4) [ "1-3", 6, 8, "10-12" ]

我最初认为这是由于数组索引混淆造成的,但使用 index-1s 并没有解决问题。有没有其他人在 JavaScript 的拼接上遇到过类似的问题,如果有,你是如何让它工作的?

【问题讨论】:

    标签: javascript arrays


    【解决方案1】:

    问题在于一行代码:

            testArray.splice(i, j, range);
    

    根据MDN,第二个参数指定要删除数组中的多少元素。

    deleteCount

    一个整数,表示数组中要从开始删除的元素数。

    但是,代码将此参数定义为要从中删除的最后一个数组的索引:

        let j = i + 1;
    

    解决方案是在将i 和j 之间的差异传递给splice 之前:

            testArray.splice(i, j - i, range);
    

    【讨论】:

      【解决方案2】:

      当你这样做时:

      testArray.splice(i, j, range);
      

      您忘记了j 是您要擦除的数组的右极限索引,因此您需要减去i 即左极限:

      testArray.splice(i, j - i, range);
      

      let testArray = [1, 2, 3, 6, 8, 10, 11, 12, 15, 18];
      
      for (i = 0; i < testArray.length; i++) {
        let consecutives = [];
        consecutives.push(testArray[i]);
        let j = i + 1;
        while (j < testArray.length) {
          if (testArray[j] == (testArray[j - 1] + 1)) {
            consecutives.push(testArray[j]);
            j++;
          } else {
            break;
          }
        }
        if (consecutives.length > 2) {  // doesn´t it should be > 1 ??
          let range = String(testArray[i]) + "-" + String(testArray[j - 1]);
          console.log(testArray);
          console.log(testArray[i]);
          console.log(testArray[j]);
          testArray.splice(i, j - i, range);
        }
      }
      
      console.log(testArray);

      【讨论】:

        猜你喜欢
        • 2019-08-03
        • 2010-10-04
        • 2023-01-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多