JavaScript equivalent of PHP's in_array()

2019-01-02 20:08发布

Is there a way in JavaScript to compare values from one array and see if it is in another array?

Similar to PHP's in_array function?

17条回答
ら面具成の殇う
2楼-- · 2019-01-02 20:32

There is now Array.prototype.includes:

The includes() method determines whether an array includes a certain element, returning true or false as appropriate.

var a = [1, 2, 3];
a.includes(2); // true 
a.includes(4); // false

Syntax

arr.includes(searchElement)
arr.includes(searchElement, fromIndex)
查看更多
回忆,回不去的记忆
3楼-- · 2019-01-02 20:33

Add this code to you project and use the object-style inArray methods

if (!Array.prototype.inArray) {
    Array.prototype.inArray = function(element) {
        return this.indexOf(element) > -1;
    };
} 
//How it work
var array = ["one", "two", "three"];
//Return true
array.inArray("one");
查看更多
浮光初槿花落
4楼-- · 2019-01-02 20:38

There is a project called Locutus, it implements PHP functions in Javascript and in_array() is included, you can use it exactly as you use in PHP.

Examples of use:

in_array('van', myArray);

in_array(1, otherArray, true); // Forcing strict type
查看更多
与风俱净
5楼-- · 2019-01-02 20:41

If the indexes are not in sequence, or if the indexes are not consecutive, the code in the other solutions listed here will break. A solution that would work somewhat better might be:

function in_array(needle, haystack) {
    for(var i in haystack) {
        if(haystack[i] == needle) return true;
    }
    return false;
}

And, as a bonus, here's the equivalent to PHP's array_search (for finding the key of the element in the array:

function array_search(needle, haystack) {
    for(var i in haystack) {
        if(haystack[i] == needle) return i;
    }
    return false;
}
查看更多
回忆,回不去的记忆
6楼-- · 2019-01-02 20:42

With Dojo Toolkit, you would use dojo.indexOf(). See dojo.indexOf for the documentation, and Arrays Made Easy by Bryan Forbes for some examples.

查看更多
爱死公子算了
7楼-- · 2019-01-02 20:43

I found a great jQuery solution here on SO.

var success = $.grep(array_a, function(v,i) {
    return $.inArray(v, array_b) !== -1;
}).length === array_a.length;

I wish someone would post an example of how to do this in underscore.

查看更多
登录 后发表回答