猿问

无法从 for ((i = 0; i < koniec.length; i++)

在我的 JS 脚本中,我试图通过 silnia() 索引一个返回数组的函数,我可以手动执行该操作而没有问题:silnia(5)[1] 但是当我尝试使用i来自 for 循环的不起作用。


koniec = [1,2,3];


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

    // Returns only undefined:

    console.log(silnia(5)[i]);


    // Works no problem:

    // console.log(silnia(5)[2]);

}



function silnia(n){

    var wynikSilni = [];


    for(i = 1; i < (n + 1); i++){

        wynikSilni.push(i);

    }


    return wynikSilni;    

}


陪伴而非守候
浏览 238回答 3
3回答

守着一只汪

您没有使用var,let或const语句来声明i,因此它被视为全局变量。这意味着i您在silnia函数中使用的相同我在for它外部的循环中使用的相同;本质上,它外面的循环运行一次,silniai增加到 6,一旦它返回到for全局范围内的循环,它就会停止,因为i>koniec.length(ETA:它然后尝试访问,sylnia(5)[6]因为i在那个时间点等于 6,这是未定义的)试试这个:function silnia(n) {&nbsp; &nbsp; var wynikSilni = [];&nbsp; &nbsp; for (var i = 1; i < (n + 1); i++) {&nbsp; &nbsp; &nbsp; &nbsp; wynikSilni.push(i);&nbsp; &nbsp; }&nbsp; &nbsp; return wynikSilni;}koniec = [1, 2, 3];for (var i = 0; i < koniec.length; i++) {&nbsp; &nbsp; // Returns only undefined:&nbsp; &nbsp; console.log(silnia(5)[i]);&nbsp; &nbsp; // Works no problem:&nbsp; &nbsp; // console.log(silnia(5)[2]);}

ibeautiful

现在是 2019 年,Arrays 有很多有用的方法可以消除设置和管理循环计数器的需要,正如其他人指出的那样,这是您问题的根源。Array.forEach() 是其中最简单的,将有助于大大简化您的问题:koniec = [1,2,3];// Loop over the knoiec array// .forEach requires a callback function to execute// upon each loop iteration. That function will automatically// be passed 3 arguments: the array item, the item index, the arraykoniec.forEach(function(item, index){&nbsp; &nbsp; console.log(silnia(5)[index]);});function silnia(n){&nbsp; &nbsp; var wynikSilni = [];&nbsp; &nbsp; for(i = 1; i < (n + 1); i++){&nbsp; &nbsp; &nbsp; &nbsp; wynikSilni.push(i);&nbsp; &nbsp; }&nbsp; &nbsp; return wynikSilni;&nbsp; &nbsp;&nbsp;}

慕盖茨4494581

您需要声明变量,否则所有函数都使用全局变量。function silnia(n) {&nbsp; &nbsp; var wynikSilni = [];&nbsp; &nbsp; for (var i = 1; i < (n + 1); i++) { // use var or let&nbsp; &nbsp; &nbsp; &nbsp; wynikSilni.push(i);&nbsp; &nbsp; }&nbsp; &nbsp; return wynikSilni;}var koniec = [1, 2, 3];for (var i = 0; i < koniec.length; i++) { // use var or let&nbsp; &nbsp; console.log(silnia(5)[i]);}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答