简体   繁体   English

forEach数组javascript不完整

[英]forEach array javascript incomplete

UPDATED 更新

I am trying to build an array by calling a callback function and feeding it with values from other arrays. 我正在尝试通过调用回调函数并使用其他数组中的值来填充数组。 However, I get only few values and I cannot understand why. 但是,我得到的值很少,我不明白为什么。

the structure is like: 结构如下:

var sortedData = [];

arrayProvidingTheValues.forEach(pushEl,sortedData);

and the callback function is 回调函数是

function pushEl(element,index) {
   console.log("pushEl called");
   this[index] = element;
}

input: 输入:

saisineArray = {obj1, obj2 obj3, obj4, obj5, obj6};
contratArray = {obj21, obj22 obj23, obj24, obj25, obj26};
intervalNb = 5;

expected output 预期产量

 sortedData = {obj1, obj2 obj3, obj4, obj5, obj6,obj21, obj22 obj23, obj24, obj25,obj6,obj26};

PS: this is the detailled code to show you in more detail. PS:这是详细代码,向您详细介绍。

for (var k = 0; k < intervalNb; k++) {
    if (k * interval >= saisineArray.length) {
    } else if ((k + 1) * interval >= saisineArray.length) {
        saisineArray.slice(k * interval, saisineArray.length).forEach(pushEl, sortedData);
    } else {
        saisineArray.slice(k * interval, (k + 1) * interval).forEach(pushEl, sortedData);
    }
    if (k * interval >= contratArray.length) {
    } else if ((k + 1) * interval >= contratArray.length) {
        contratArray.slice(k * interval, contratArray.length).forEach(pushEl, sortedData);
    } else {
        contratArray.slice(k * interval, (k + 1) * interval).forEach(pushEl, sortedData);
    }
}

Instead of this[index] = element; 代替this[index] = element; try this.push(element); 试试this.push(element);

What you're doing now is on every execution of forEach(pushEl) you are overwriting the sortedData array starting from index 0. 现在要做的是在每次执行forEach(pushEl) ,都将覆盖从索引0开始的sortedData数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM