简体   繁体   中英

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.

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; try 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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