函数中的for循环在调用函数时不返回索引变量

问题描述 投票:0回答:2

我试图编写一个函数,当它被调用时,将从函数内的for循环返回索引变量的值。

这是我的代码:

function myFunction() {
    for(var i = 0; i++) {
        return i;
    }

    alert(i);
}

myFunction();

如果我抛弃该函数,for循环可以正常工作,如果我用JavaScript-“alert”替换“return”。我想要实现的是for循环的结果仅在调用函数时被警告。

javascript
2个回答
0
投票

你的循环无效,它缺少停止条件。你需要在for循环中指定另一个块,否则会抛出错误。

for(var i = 0; i<10; i++)

如果你的循环是正确的,使用return语句将退出function,结果for循环也将结束。所以return语句之后的所有代码都将被忽略,包括你的alert(i)语句。

换句话说,return之后的所有代码都将被省略和忽略,因为函数调用已经因return关键字而结束。

Edit:

如果您正在尝试创建数组或数字列表并在调用函数时返回它,那么您应该这样做:

function myFunction() {
    var array = [];
    for(var i = 0; i<10; i++) {
        array.push(i);
    }
    return array;
}

alert(myFunction());

-1
投票

map()在数组的每个元素上运行一个函数,并始终返回每个函数结果的数组。原则上有两个演示都是相同的。

详细信息在演示中进行了评论

演示1

/* Collect all divs into a NodeList with
|| querySelectorAll()
|| Then convert the NodeList into an array with
|| Array.from()
*/
var divs = Array.from(document.querySelectorAll('div'));

/* Run the array method map() on divs[]
|| map() will run a function on each element of
|| an array. It will return a new array that
|| comprises of each of the functions' return.
*/
var INDEX_VALUE = divs.map(function(div, idx, divs) {

      // Get the text of each div
      var txt = div.textContent;

      // Display INDEX VALUE and text in console
      console.log('Index: ' + idx + ' Content: '+txt);

        // Return an array of all the results
        return idx;
      });

    console.log(INDEX_VALUE);
<div>01</div>
<div>ponies</div>
<div>unicorns</div>
<div>qwerty</div>
<div>foo</div>
<div>bar</div>
<div>hello</div>
<div>world</div>

演示2

var arr = ['01', 'ponies', 'unicorns', 'foo', 'bar', 'hello', 'world'];

var INDEX_VALUE = arr.map(function(ele, idx, arr) {
  var size = ele.length;
  console.log('Index: ' + idx + ' String: ' + ele + ' Chars: ' + size);
  return idx;

});
© www.soinside.com 2019 - 2024. All rights reserved.