JavaScript 相当于 PHP 的 in_array()

发布于 2024-07-17 14:05:19 字数 155 浏览 10 评论 0原文

JavaScript 有没有一种方法可以比较一个数组中的值并查看它是否在另一个数组中?

类似于 PHP 的 in_array 函数?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(21

乜一 2024-07-24 14:05:19

不,它没有。 因此,大多数流行的库都在其实用程序包中附带了一个库。 查看 jQuery 的 inArray 和 Prototype 的Array.indexOf

jQuery 的实现就像您所期望的一样简单:

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

如果您正在处理数量合理的数组元素,上面的方法就可以很好地实现这一点。

编辑:哎呀。 我什至没有注意到你想查看一个数组是否在另一个数组内。 根据 PHP 文档,这是 PHP 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 。 这就是你想要的:

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

请注意,我故意没有扩展数组原型,因为这样做通常是一个坏主意。

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'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.

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

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;
}

And this my test of the above on it:

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

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

柒夜笙歌凉 2024-07-24 14:05:19

现在有 Array.prototype.includes

includes()方法判断一个数组是否包含某个
元素,根据需要返回 true 或 false。

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

语法

arr.includes(searchElement)
arr.includes(searchElement, fromIndex)

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)
高跟鞋的旋律 2024-07-24 14:05:19

Array.indexOf 引入于JavaScript 1.6,但旧版浏览器不支持。 值得庆幸的是,Mozilla 的小伙子们已经完成了所有艰苦的工作 为您提供,并为您提供了此兼容性:

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;
  };
}

甚至还有一些方便的使用片段,供您享受脚本编写的乐趣。

Array.indexOf was introduced in JavaScript 1.6, but it is not supported in older browsers. Thankfully the chaps over at Mozilla have done all the hard work for you, and provided you with this for compatibility:

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;
  };
}

There are even some handy usage snippets for your scripting pleasure.

天赋异禀 2024-07-24 14:05:19

PHP方式:

if (in_array('a', ['a', 'b', 'c'])) {
   // do something if true
}

我的JS解决方案:

if (['a', 'b', 'c'].includes('a')) {
   // do something if true
}

PHP way:

if (in_array('a', ['a', 'b', 'c'])) {
   // do something if true
}

My solution in JS:

if (['a', 'b', 'c'].includes('a')) {
   // do something if true
}
蓝咒 2024-07-24 14:05:19

您可以简单地使用“includes”函数,如 w3schools 课程中所述,

它看起来像

let myArray = ['Kevin', 'Bob', 'Stuart'];
if( myArray.includes('Kevin'))
console.log('Kevin is here');

You can simply use the "includes" function as explained in this lesson on w3schools

it looks like

let myArray = ['Kevin', 'Bob', 'Stuart'];
if( myArray.includes('Kevin'))
console.log('Kevin is here');

梦在深巷 2024-07-24 14:05:19

如果索引不按顺序,或者索引不连续,则此处列出的其他解决方案中的代码将会损坏。 一个更好的解决方案可能是:

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

而且,作为奖励,这里相当于 PHP 的 array_search (用于查找数组中元素的键:

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

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;
}
愿与i 2024-07-24 14:05:19

有一个名为 Locutus 的项目,它在 Javascript 中实现了 PHP 函数和 in_array() 已包含在内,您可以像在 PHP 中一样使用它。

使用示例:

in_array('van', myArray);

in_array(1, otherArray, true); // Forcing strict type

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
深爱不及久伴 2024-07-24 14:05:19

jQuery 解决方案可用,请在此处查看文档:
http://api.jquery.com/jquery.inarray/

$.inArray( 10, [ 8, 9, 10, 11 ] );

jQuery solution is available, check the ducumentation here:
http://api.jquery.com/jquery.inarray/

$.inArray( 10, [ 8, 9, 10, 11 ] );
渔村楼浪 2024-07-24 14:05:19
var a = [1,2,3,4,5,6,7,8,9];

var isSixInArray = a.filter(function(item){return item==6}).length ? true : false;

var isSixInArray = a.indexOf(6)>=0;
var a = [1,2,3,4,5,6,7,8,9];

var isSixInArray = a.filter(function(item){return item==6}).length ? true : false;

var isSixInArray = a.indexOf(6)>=0;
遇见了你 2024-07-24 14:05:19

如果您只想检查数组中是否有单个值,那么 Paolo 的代码就可以完成这项工作。 如果您想检查两个数组共有哪些值,那么您需要这样的东西(使用 Paolo 的 inArray 函数):

function arrayIntersect(a, b) {
    var intersection = [];

    for(var i = 0; i < a.length; i++) {
        if(inArray(b, a[i]))
            intersection.push(a[i]);
    }

    return intersection;
}

这将返回一个包含 a中的值的数组>b。 (从数学上讲,这是两个数组的交集。)

编辑:请参阅 Paolo 编辑的代码,了解您的问题的解决方案问题。 :)

If you only want to check if a single value is in an array, then Paolo's code will do the job. If you want to check which values are common to both arrays, then you'll want something like this (using Paolo's inArray function):

function arrayIntersect(a, b) {
    var intersection = [];

    for(var i = 0; i < a.length; i++) {
        if(inArray(b, a[i]))
            intersection.push(a[i]);
    }

    return intersection;
}

This wil return an array of values that are in both a and b. (Mathematically, this is an intersection of the two arrays.)

EDIT: See Paolo's Edited Code for the solution to your problem. :)

眼眸里的那抹悲凉 2024-07-24 14:05:19

如果您需要所有 PHP 可用参数,请使用以下命令:

function in_array(needle, haystack, argStrict) {
    var key = '', strict = !!argStrict;
    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;
            }
        }
    }
    else {
        for (key in haystack) {
            if (haystack[key] == needle) {
                return true;
            }
        }
    }
    return false;
}

If you need all the PHP available parameters, use this:

function in_array(needle, haystack, argStrict) {
    var key = '', strict = !!argStrict;
    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;
            }
        }
    }
    else {
        for (key in haystack) {
            if (haystack[key] == needle) {
                return true;
            }
        }
    }
    return false;
}
撩发小公举 2024-07-24 14:05:19

将此代码添加到您的项目中并使用对象样式的 inArray 方法

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");

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");
櫻之舞 2024-07-24 14:05:19
function in_array(needle, haystack){

    return haystack.indexOf(needle) !== -1;
}
function in_array(needle, haystack){

    return haystack.indexOf(needle) !== -1;
}
祁梦 2024-07-24 14:05:19

对于 Dojo Toolkit,您可以使用 dojo.indexOf()。 请参阅 dojo.indexOf 了解文档,以及< em>Arrays Made Easy,作者:Bryan Forbes,提供了一些示例。

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

风筝有风,海豚有海 2024-07-24 14:05:19
haystack.find(value => value == needle)

其中 haystack 是一个数组,needle 是数组中的一个元素。 如果未找到元素,则返回未定义的元素,否则返回相同的元素。

haystack.find(value => value == needle)

where haystack is an array and needle is an element in array. If element not found will be returned undefined else the same element.

墨小墨 2024-07-24 14:05:19
function in_array(what, where) {
    var a=false;
    for (var i=0; i<where.length; i++) {
        if(what == where[i]) {
            a=true;
            break;
        }
    }
    return a;
}
function in_array(what, where) {
    var a=false;
    for (var i=0; i<where.length; i++) {
        if(what == where[i]) {
            a=true;
            break;
        }
    }
    return a;
}
美人骨 2024-07-24 14:05:19

我找到了一个很棒的 jQuery 解决方案 这里关于SO。

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

我希望有人能发布一个如何在下划线中执行此操作的示例。

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.

骄兵必败 2024-07-24 14:05:19

带有 underscorein_array 的等效项是 _.indexOf

示例:

_.indexOf([3, 5, 8], 8); // 返回 2,索引 8
_.indexOf([3, 5, 8], 10); // 返回-1,未找到

An equivalent of in_array with underscore is _.indexOf

Examples:

_.indexOf([3, 5, 8], 8); // returns 2, the index of 8
_.indexOf([3, 5, 8], 10); // returns -1, not found

再可℃爱ぅ一点好了 2024-07-24 14:05:19

如果您打算在课堂上使用它,并且希望它具有功能性(并且可以在所有浏览器中工作):

inArray: function(needle, haystack)
{
    var result = false;

    for (var i in haystack) {
        if (haystack[i] === needle) {
            result = true;
            break;
        }
    }

    return result;
}

希望它对某人有帮助:-)

If you are going to use it in a class, and if you prefer it to be functional (and work in all browsers):

inArray: function(needle, haystack)
{
    var result = false;

    for (var i in haystack) {
        if (haystack[i] === needle) {
            result = true;
            break;
        }
    }

    return result;
}

Hope it helps someone :-)

他不在意 2024-07-24 14:05:19
var value = 'a';
var array = ['a', 'b', 'c'];
if(array.indexOf(value)){
    // exists in array
} else {
   // Not exists in array
}
var value = 'a';
var array = ['a', 'b', 'c'];
if(array.indexOf(value)){
    // exists in array
} else {
   // Not exists in array
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文