【问题标题】:splice inside for loop return wrong values JAVASCRIPTfor 循环内的拼接返回错误值 JAVASCRIPT
【发布时间】:2021-06-25 03:09:35
【问题描述】:

我想将我的数组的内容分成 4 份,为此我首先需要知道每个分割数组集的内容是什么,我为此使用 Math.ceil。

results = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']; #lenght is 8
let half = Math.ceil(results.length / 4) # half is 2
let whole = [] #i want to insert the spliced value into this array
let j = 0;
let x
for (i = 0; i < 4; i++) {
    console.log("j:" + j)
    console.log("half: " + half)
    x = results.splice(j, half)
    console.log(x)
    j = j + half;
}

这是我的错误输出:

j:0
half: 2
[ 'a', 'b' ] #this is correct
j:2
half: 2
[ 'e', 'f' ] #this is wrong, it should be ['c','d']
j:4
half: 2
[] #this is wrong, should be ['e','d']
j:6
half: 2
[]#also wrong, should be ['f','g',]

当我在 for 循环之外测试它时,它工作正常,使用索引 0,2 - 2,2 - 4, 2 -6,2。 可能是什么错误?

【问题讨论】:

    标签: javascript splice


    【解决方案1】:

    Splice 方法更改数组的内容(通过删除、替换或添加)。你应该使用slice,结尾是i * 2 + half

    results = ["a", "b", "c", "d", "e", "f", "g", "h"]; // #lenght is 8
    let half = Math.ceil(results.length / 4); // # half is 2
    let whole = []; //#i want to insert the spliced value into this array
    let j = 0;
    let x;
    for (i = 0; i < 4; i++) {
    
      // change the end so that it will take next 2 element pos dynamically
      const end = i * 2 + half;
      x = results.slice(j, end);
      j = j + half;
      whole.push(x);
    }
    
    console.log(whole);

    【讨论】:

      猜你喜欢
      • 2016-12-30
      • 2016-11-29
      • 2011-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-28
      相关资源
      最近更新 更多