接头和切片的可能错误/误解

时间:2018-10-04 22:37:26

标签: javascript jquery

我有下一个循环:

    rolling_average_delta_follower=[];
    followers=[32,34,36,38,40,42,44,46,48,50,52,54,56] // .length = 12
    delta_followers=[50,52,54,56,58,60,62,64,66,68,70,72,74]  // leng= 12

     for (i = 0; i < followers.length ; i++) {

                copie = delta_followers.slice(0); //creates duplicate of array delta_followers so I keep source original and not cut from it
                copie.splice(7,i) // supposed to create an array that contains numbers from 50 to 64 -> next time the for executes it should go 52 to 66 and so on
                console.log(copie)
                for (i = 0; i < 8; i++) {  // the 7 numbers added previously in the one array are getting summed up
                    totalx += copie[i]
                }
                rolling_average_delta_follower.push(totalx) // the sum of each array previously created is getting added to the main array where I need the data.


        }

一切都好,直到我尝试实际执行它为止,最后出现了一个永久循环,似乎无法逃脱。

任何帮助将不胜感激。

谢谢!

2 个答案:

答案 0 :(得分:1)

问题在这里:

for (i = 0; i < 8; i++) {  // the 7 numbers added previously in the one array are getting summed up
    totalx += copie[i]
}

通过此代码,您将覆盖上面循环中使用的i。 只需在此处使用另一个变量名。 (j吗?)

答案 1 :(得分:1)

要使用数组运算符复制数组。

const copy = [...original];

要对数组的值求和,请使用reduce。

const sum = array.reduce((sum, item) => sum + item, 0);