JavaScript的等价于PHP的in_array() [英] JavaScript equivalent of PHP's in_array()

查看:655
本文介绍了JavaScript的等价于PHP的in_array()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JavaScript中有没有办法比较一个数组的值,看看它是否在另一个数组中?

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

类似于PHP的 in_array 功能?

Similar to PHP's in_array function?

推荐答案

不,它没有。出于这个原因,大多数流行的库都带有一个实用程序包。查看jQuery的 inArray 和Prototype的 Array.indexOf 以获取示例。

No, it doesn't have one. For this reason most popular libraries come with one in their utility packages. Check out jQuery's inArray and Prototype's Array.indexOf for examples.

jQuery的实现非常简单:

jQuery's implementation of it is as simple as you might expect:

function inArray(needle, haystack) {
    var length = haystack.length;
    for(var i = 0; i < length; i++) {
        if(haystack[i] == needle) return true;
    }
    return false;
}

如果您正在处理数量明确的数组元素,上面的内容将会执行很好。

If you are dealing with a sane amount of array elements the above will do the trick nicely.

编辑:哎呀。我甚至没有注意到你想看看阵列是否在另一个内部。根据PHP文档,这是PHP的 in_array <的预期行为/ a>:

EDIT: Whoops. I didn't even notice you wanted to see if an array was inside another. According to the PHP documentation this is the expected behavior of PHP's in_array:

$a = array(array('p', 'h'), array('p', 'r'), 'o');

if (in_array(array('p', 'h'), $a)) {
    echo "'ph' was found\n";
}

if (in_array(array('f', 'i'), $a)) {
    echo "'fi' was found\n";
}

if (in_array('o', $a)) {
    echo "'o' was found\n";
}

// Output:
//  'ph' was found
//  'o' was found

Chris和Alex发布的代码不遵循此行为。 Alex是Prototype的indexOf的官方版本,而Chris的更像是PHP的 array_intersect 。这样做你想要的:

The code posted by Chris and Alex does not follow this behavior. Alex's is the official version of Prototype's indexOf, and Chris's is more like PHP's array_intersect. This does what you want:

function arrayCompare(a1, a2) {
    if (a1.length != a2.length) return false;
    var length = a2.length;
    for (var i = 0; i < length; i++) {
        if (a1[i] !== a2[i]) return false;
    }
    return true;
}

function inArray(needle, haystack) {
    var length = haystack.length;
    for(var i = 0; i < length; i++) {
        if(typeof haystack[i] == 'object') {
            if(arrayCompare(haystack[i], needle)) return true;
        } else {
            if(haystack[i] == needle) return true;
        }
    }
    return false;
}

这是我对上面的测试:

var a = [['p','h'],['p','r'],'o'];
if(inArray(['p','h'], a)) {
    alert('ph was found');
}
if(inArray(['f','i'], a)) {
    alert('fi was found');
}
if(inArray('o', a)) {
    alert('o was found');
}  
// Results:
//   alerts 'ph' was found
//   alerts 'o' was found

请注意,我故意不扩展Array原型,因为这通常是一个坏主意。

Note that I intentionally did not extend the Array prototype as it is generally a bad idea to do so.

这篇关于JavaScript的等价于PHP的in_array()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆