我可能有 Javascript 初学者问题:
var countries = [
"Bangladesh", "Germany", "Pakistan"];
function testexistence(arr, input) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] != input) {
alert("not exist");
arr.push(input);
break;
} else {
alert("already exist ");
}
}
}
testexistence(countries, "UK");
testexistence(countries, "Pakistan");
testexistence(countries, "UK");
我期望的是:当我再次调用“UK”函数时,它显示“已经存在”;但这并没有发生。我不想玩“原型(prototype)”或定义自己的原型(prototype)。我只需要一行解决方案。
我的代码中有一个用例,我必须在数组中插入一个新值,并且在下一个循环中我必须检查该值;但我最终插入了一个现有的值...
为什么我最终要插入现有值以及为什么此检查 (arr[i] != input)
失败?
另请解释一下为什么上述代码无法按预期工作
最佳答案
您需要搜索整个数组才能确定它不存在。
function testexistence(arr, input) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] === input) {
alert("already exists");
return; // halt the search by returning
}
}
// If we're here, we never returned inside the loop, so it wasn't found.
arr.push(input);
alert("did not exist, now it does");
}
<小时/>
我可能会将您的函数命名为 addUnique
或其他名称,而不是 testexistence
。
关于javascript - 这是 Javascript Closure 用例吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16151742/