真的不确定这里发生了什么,因为我是 JavaScript 的新手,但实际上无法弄清楚,即使在阅读了像这样的其他帖子之后:Simple function returns 'undefined' value。出于某种原因,当我的代码放在函数中时,它返回“未定义”而不是真或假。
如果我使用没有函数的代码并a
在第一行定义 var ,它可以正常工作:
var a = "wjebh ghbui ayub";
var b = (a.split(' ').join('')).split('a'); // creates array
var trueOrFalse = b.map(function(c, i){ // puts into array true/false for each index
if (c[2] == 'b') {
console.log('value: ' + c[2] + ' is b; true');
return true;
} else {
console.log('false');
return false;
}
});
var answer = function(el) {
// checks whether any element is true
return el === true;
};
trueOrFalse.some(answer); // return true/false
但是当我将它添加到函数中时,它不起作用。
function bThreeAfterA(a) {
var b = (a.split(' ').join('')).split('a'); // creates array
var trueOrFalse = b.map(function(c, i){ // puts into array true/false for each index
if (c[2] == 'b') {
console.log('value: ' + c[2] + ' is b; true');
return true;
} else {
console.log('false');
return false;
}
});
var answer = function(el) {
// checks whether any element is true
return el === true;
};
trueOrFalse.some(answer); // return true/false
}
即使将其放入 IIFE,它也无法正常工作:
(function(){
var a = "wjebh ghbui ayub";
var b = (a.split(' ').join('')).split('a'); // creates array
var trueOrFalse = b.map(function(c, i){ // puts into array true/false for each index
if (c[2] == 'b') {
console.log('value: ' + c[2] + ' is b; true');
return true;
} else {
console.log('false');
return false;
}
});
var answer = function(el) {
// checks whether any element is true
return el === true;
};
trueOrFalse.some(answer); // return true/false
})();
我觉得我在这里做了一些非常愚蠢的事情,大多数人很容易发现。有人可以解释我在这里做错了什么吗?大概这是某种初学者语法错误。任何阅读资源的链接也会有所帮助。
我们都去过那里。
试一试吧。
function bThreeAfterA(a) {
var b = (a.split(' ').join('')).split('a'); // creates array
var trueOrFalse = b.map(function(c, i){ // puts into array true/false for each index
if (c[2] == 'b') {
console.log('value: ' + c[2] + ' is b; true');
return true;
} else {
console.log('false');
return false;
}
});
var answer = function(el) {
// checks whether any element is true
return el === true;
};
return trueOrFalse.some(answer); //ACTUALLY return true/false
}
console.log("Answer: " + bThreeAfterA("wjebh ghbui ayub")); // Returns true.
当您对块范围之外的变量进行操作时,它们会持续存在。当他们在里面时,他们消失了。
因此,它“有效”,但当你在函数中使用它时它“无效”。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句