开发者

Find element in Javascript Array [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Javascript - array.contains(obj)

What's wrong with this:

开发者_如何学Govar zipCodes =(['90001','90002','90003']);

Test if the value exists in the array zipCodes

if('90001' in zipCodes) {
  alert('True');
};


The in operator looks at property names, not values.

Because it's an Array, the property names will be the indices of the Array.

If you're only supporting a modern environment, you could use Array.prototype.indexOf().

if(zipCodes.indexOf('90001') > -1) {

If you need to support environments that don't have .indexOf(), you could implement the MDN fix.

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
        "use strict";

        if (this === void 0 || this === null) throw new TypeError();

        var t = Object(this);
        var len = t.length >>> 0;
        if (len === 0) return -1;

        var n = 0;
        if (arguments.length > 0) {
            n = Number(arguments[1]);
            if (n !== n) // shortcut for verifying if it's NaN
            n = 0;
            else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) n = (n > 0 || -1) * Math.floor(Math.abs(n));
        }

        if (n >= len) return -1;

        var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);

        for (; k < len; k++) {
            if (k in t && t[k] === searchElement) return k;
        }
        return -1;
    };
}


If you want to check if the array contains a given value, you can use the indexOf method to check for the position of an item. If the item is not found in the array, a -1 is returned:

var zipCodes =(['90001','90002','90003']);
zipCodes.indexOf('90001') // 0
zipCodes.indexOf('90002') // 1
zipCodes.indexOf('90003') // 2
zipCodes.indexOf('90004') // -1

if(zipCodes.indexOf('90001') != -1) {
  alert('True');
};

See more at http://freewebdesigntutorials.com/javaScriptTutorials/jsStringObject/indexOfMethod.htm


Use an object instead. If this is all you're trying to do with the array, then an object is a much more efficient way to do a lookup list.

var zipCodes = {"90001": true, "90002": true, "90003": true};

if ('90001' in zipCodes) {
    alert('True');
}

jsfiddle here to see it work: http://jsfiddle.net/jfriend00/ZNGTq/


You need something like this:

var zipCodes =(['90001','90002','90003']);

if (zipCodes.has('90001')) {
  ....
}

    Array.prototype.has=function(v){
        for (i=0;i<this.length;i++){
           if (this[i]==v) return i;
        }
        return false;
    }

See this for more info:

http://snook.ca/archives/javascript/testing_for_a_v

....


Because in checks for a property of an object. Check this out for converting "in object" to "in array": Testing for a Value in JavaScript Array

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜