【问题标题】:does javascript have an exists() or contains() function for an arrayjavascript 是否有数组的 exists() 或 contains() 函数
【发布时间】:2010-01-15 03:02:02
【问题描述】:

还是只需要循环并检查每个元素?

【问题讨论】:

    标签: javascript jquery arrays


    【解决方案1】:

    Mozilla JS 实现和其他现代 JS 引擎都采用了Array.prototype.indexOf 方法。

    [1].indexOf(1) // 0
    

    如果不包含它,则返回 -1。

    IE当然也可能其他浏览器没有,官方代码:

    if (!Array.prototype.indexOf)
    {
      Array.prototype.indexOf = function(elt /*, from*/)
      {
        var len = this.length >>> 0;
    
        var from = Number(arguments[1]) || 0;
        from = (from < 0)
             ? Math.ceil(from)
             : Math.floor(from);
        if (from < 0)
          from += len;
    
        for (; from < len; from++)
        {
          if (from in this &&
              this[from] === elt)
            return from;
        }
        return -1;
      };
    }
    

    【讨论】:

      【解决方案2】:

      如果你使用 jQuery:jQuery.inArray( value, array )

      更新:指向新 jQuery API 的 URL

      【讨论】:

        【解决方案3】:

        您可以查看 Javascript 1.6 的某些功能。

        https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Working_with_Arrays#Introduced_in_JavaScript_1.6

        如果您只想知道它是否在其中,您可以使用indexOf,例如,这将满足您的需求。

        更新:

        如果您访问此页面,http://www.hunlock.com/blogs/Mastering_Javascript_Arrays,您可以找到在 IE 和任何其他没有您想要使用的内置功能的浏览器上使用的功能。

        【讨论】:

          【解决方案4】:

          这是拥有自己的indexOf 方法的一种方法。此版本利用环境中存在的Array.prototype.indexOf 方法;否则,它使用自己的实现。

          (此代码已经过测试,但我不保证它在所有情况下的正确性。)

          // If Array.prototype.indexOf exists, then indexOf will contain a closure that simply
          // calls Array.prototype.indexOf. Otherwise, indexOf will contain a closure that
          // *implements* the indexOf function. 
          // 
          // The net result of using two different closures is that we only have to
          // test for the existence of Array.prototype.indexOf once, when the script
          // is loaded, instead of every time indexOf is called.
          
          var indexOf = 
              (Array.prototype.indexOf ? 
               (function(array, searchElement, fromIndex) {
                   return array.indexOf(searchElement, fromIndex);
               })
               :
               (function(array, searchElement, fromIndex)
                {
                    fromIndex = Math.max(fromIndex || 0, 0);
                    var i = -1, len = array.length;
                    while (++i < len) {
                        if (array[i] === searchElement) {
                            return i;
                        }
                    }
                    return -1;
                })
              );
          

          【讨论】:

            猜你喜欢
            • 2010-11-08
            • 2021-02-22
            • 2016-04-27
            • 2011-08-20
            • 2013-05-02
            • 1970-01-01
            • 2016-06-19
            • 2019-10-21
            • 2013-10-14
            相关资源
            最近更新 更多