开发者社区> 问答> 正文

确定数组是否包含值

我需要确定数组中是否存在值。

我正在使用以下功能:

Array.prototype.contains = function(obj) { var i = this.length; while (i--) { if (this[i] == obj) { return true; } } return false; }

上面的函数总是返回false。

数组值和函数调用如下:

arrValues = ["Sam","Great", "Sample", "High"] alert(arrValues.contains("Sam"));

展开
收起
保持可爱mmm 2020-01-08 17:13:00 488 0
1 条回答
写回答
取消 提交回答
  • var contains = function(needle) { // Per spec, the way to identify NaN is that it is not equal to itself var findNaN = needle !== needle; var indexOf;

    if(!findNaN && typeof Array.prototype.indexOf === 'function') {
        indexOf = Array.prototype.indexOf;
    } else {
        indexOf = function(needle) {
            var i = -1, index = -1;
    
            for(i = 0; i < this.length; i++) {
                var item = this[i];
    
                if((findNaN && item !== item) || item === needle) {
                    index = i;
                    break;
                }
            }
    
            return index;
        };
    }
    
    return indexOf.call(this, needle) > -1;
    

    };

    您可以像这样使用它:

    var myArray = [0,1,2], needle = 1, index = contains.call(myArray, needle); // true

    2020-01-08 17:13:12
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
重新定义计算的边界 立即下载
低代码开发师(初级)实战教程 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载