【问题标题】:Is this JavascriptClosure usecase?这是 Javascript 闭包用例吗?
【发布时间】:2013-04-22 16:13:03
【问题描述】:

我可能有初学者 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”调用该函数时,它显示“已经存在”;但这并没有发生。我不想玩“原型”或定义自己的。我只需要一种解决方案。

我的代码中有一个用例,我必须在数组中插入一个新值,并且在接下来的循环中我必须检查该值;但我最终要插入一个现有值...

为什么我最终要插入现有值以及为什么此检查 (arr[i] != input) 失败?

还请解释一下,为什么上面的代码不能正常工作

【问题讨论】:

  • 您可能应该每次都推送输入,而不是“UK”。它不工作吗?
  • testexistence 不是该函数的好名称。 pushIfUniquepushUnique 怎么样?

标签: javascript arrays closures


【解决方案1】:

您需要搜索整个数组才能确定它不存在。

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

【讨论】:

  • 既然你提供了一个解决方案,你应该推送input,而不是UK
  • @cfs:嘿,甚至没有注意到这一点。只需复制并粘贴代码。谢谢!
【解决方案2】:

试试:

function testexistence(arr, input) {
    if (!~arr.indexOf(input)) {
        arr.push(input);
    }
}

演示: http://jsfiddle.net/L9NhU/

请注意,Array.indexOf 在旧版浏览器中不可用,因此您可以使用 polyfill(或保持当前循环)。这是它的 MDN 文档,其中包括一个 polyfill:https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf

【讨论】:

  • 似乎他的代码想要添加一些在测试时不存在的东西。需要修改:D
  • 你为什么用 ~ 作为你的“在数组中?”测试?是不是比return (arr.indexOf(input) != -1)效率更高?
  • @andytuba 这是测试布尔值的更短的方法。 !~ checks for -1
  • @andytuba 这是一个位运算符,结果为0 only 用于-1(未找到该项目)。所以!~ 在数组中未找到该项目时为真。它更快,因为它在检查真实性时比比较两个项目更快,并且比较检查更快
【解决方案3】:

首先,它绝不是闭包

不管怎样,这里是the one-liner you wanted,对Ian's answer的修改

function testexistence(arr, input) {
  (!~arr.indexOf(input)) && arr.push(input);
}

我们使用了一些东西:

  • Array.indexOf 在数组中搜索您传递的第一个匹配项,如果存在则返回从零开始的值,如果不存在则返回 -1
  • !~ 是这里的一个特例,我们在这里测试-1。值~x 等于-(x+1),这使得-1 成为0(假)和所有其他非零(真)。将! 添加到组合中会使-1 成为真值而其他值是假的。
  • &amp;&amp; 评估其两侧。如果左边是“真”,则评估右边,否则不评估。它也被称为“守卫操作员”

【讨论】:

  • 您应该避免以这种方式使用&amp;&amp;。正如 JavaScript 创造者 Brendan Eich 在他的博客上指出的那样,it's an abusage。最好使用实际的if-statement。您也不会使用更多字符;只需将&amp;&amp; 转换为if 并将其放在条件的另一侧。
【解决方案4】:

你需要尝试这样的事情

var countries = ["london", "germany", "france"];


function testexistence(arr, input) {
   var isExists = false;

    for (var i = 0; i < arr.length; i++) {
        if (arr[i] == input) {
            isExists = true;
        }         
    }

    if(!isExists)
    {
        alert("Not Exists");
        arr.push(input);
    }
    else
    {
        alert("Exists");
    }
}

testexistence(countries, "UK");
testexistence(countries, "london");
testexistence(countries, "UK");

【讨论】:

    【解决方案5】:

    你可以用这个代替你的:

    function testexistence(arr, input) {
    
        for (var i = 0; i < arr.length; i++) {
            if (arr[i] == input) {
                alert("already exist ");
                return;
            }
        }
    
        //if the if part would not work, you pass to here
        alert("not exist");
        arr.push(item);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-10
      • 1970-01-01
      • 1970-01-01
      • 2010-10-07
      • 1970-01-01
      • 1970-01-01
      • 2014-10-21
      • 1970-01-01
      相关资源
      最近更新 更多