javascript - for 循环内的拼接返回错误值 JAVASCRIPT
问题描述
我想将我的数组的内容分成 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。可能是什么错误?
解决方案
拼接方法改变数组的内容(通过删除、替换或添加)。您应该使用slice与 end uptoi * 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);
推荐阅读
- android - 动态改变视图
- facebook - Facebook 市场跟踪网页变化
- python - Python 干净的代码:我应该怎么做?传递参数 vs 使用属性 vs 就地修改
- c++ - wxWidgets 中的 minimum_cocoa - 运行时应该是什么样子 - 请在此处发布屏幕截图
- c - 指针的内存分配适用于固定变量分配的字符串,但不适用于用户输入字符串
- image-processing - 性格退化模型论文中的问题
- javascript - HTML5 Canvas - 删除事件监听器
- mongodb - MongoDB,Mongoose在x时间后删除元素并接收事件
- forms - svelte 中的数据绑定复选框
- ansible - Ansible 剧本“未找到 src 中指定的路径”