【问题标题】:javascript string in list returns false列表中的 javascript 字符串返回 false
【发布时间】:2013-04-09 20:58:37
【问题描述】:

我的网站刚刚开始为以下 javascript 检查返回 false。我正在尝试了解原因。

_test = ["0e52a313167fecc07c9507fcf7257f79"]
"0e52a313167fecc07c9507fcf7257f79" in _test
>>> false
_test[0] === "0e52a313167fecc07c9507fcf7257f79"
>>> true 

有人可以帮我理解为什么吗?

【问题讨论】:

标签: javascript


【解决方案1】:

in 运算符测试属性是否在对象中。例如

var test = {
    a: 1,
    b: 2 
};

"a" in test == true;
"c" in test == false;

你想测试一个数组是否包含一个特定的对象。您应该使用 Array#indexOf 方法。

test.indexOf("0e52...") != -1 // -1 means "not found", anything else simply indicates the index of the object in the array.

MDN 上的数组#indexOf:https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf

【讨论】:

    【解决方案2】:

    来自the MDN

    如果指定的属性在 指定对象。

    它检查的是键,而不是值。

    在那里,属性键是0,而不是"0e52a313167fecc07c9507fcf7257f79"

    您可以测试0 in _testtrue

    如果要检查某个值是否在数组中,请使用indexOf

    _test.indexOf("0e52a313167fecc07c9507fcf7257f79")!==-1
    

    (IE8 需要 MDN 提供的 shim)

    【讨论】:

      【解决方案3】:

      “in”运算符在对象键中搜索,而不是值。您将不得不使用 indexOf 并注意它在以前的 IE 版本中的非实现。因此,您可能会在第一个 google 结果中找到 Array.prototype.indexOf 方法的跨浏览器实现。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-12-04
        • 1970-01-01
        • 1970-01-01
        • 2015-07-31
        • 2011-07-20
        • 2020-09-15
        • 2016-12-18
        相关资源
        最近更新 更多