我试图编写一个函数,当它被调用时,将从函数内的for循环返回索引变量的值。
这是我的代码:
function myFunction() {
for(var i = 0; i++) {
return i;
}
alert(i);
}
myFunction();
如果我抛弃该函数,for循环可以正常工作,如果我用JavaScript-“alert”替换“return”。我想要实现的是for循环的结果仅在调用函数时被警告。
你的循环无效,它缺少停止条件。你需要在for
循环中指定另一个块,否则会抛出错误。
for(var i = 0; i<10; i++)
如果你的循环是正确的,使用return
语句将退出function
,结果for
循环也将结束。所以return
语句之后的所有代码都将被忽略,包括你的alert(i)
语句。
换句话说,return
之后的所有代码都将被省略和忽略,因为函数调用已经因return
关键字而结束。
如果您正在尝试创建数组或数字列表并在调用函数时返回它,那么您应该这样做:
function myFunction() {
var array = [];
for(var i = 0; i<10; i++) {
array.push(i);
}
return array;
}
alert(myFunction());
map()在数组的每个元素上运行一个函数,并始终返回每个函数结果的数组。原则上有两个演示都是相同的。
详细信息在演示中进行了评论
/* 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>
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;
});