如果我删除namePosition,为什么警报无效? Javascript在执行时是否逐行读取(从上到下)?如果是,则警报应该起作用,因为它在返回之前首先执行/读取。
function positionIdentifier(name, nameArray) {
var namePosition;
for (i = 0; i < nameArray.length; i++) {
if (nameArray[i] == name) {
namePosition = function() {
alert("Your name is in position number " + (i + 1));
}
return namePosition;
}
}
}
name1Array = ["look", "sky", "walk", "kier"];
positionIdentifier("walk", name1Array)();
答案 0 :(得分:2)
您的函数按原样运行,但是,不需要声明/命名要返回的函数。只需返回功能。这简化了代码。此外,您没有使用var
声明循环变量或数组变量,这会导致它们变为全局变量。记得声明所有变量。
function positionIdentifier(name,nameArray){
for(var i = 0; i < nameArray.length; i++){
if(nameArray[i] == name){
return function(){
alert("Your name is in position number "+(i+1));
}
}
}
}
var name1Array = ["look","sky","walk","kier"];
positionIdentifier("walk", name1Array)();
&#13;