如何检查 JavaScript 数组中是否存在项

how to check if item exists in a javascript array

本文关键字:数组 是否 存在 JavaScript 何检查 检查      更新时间:2023-09-26

我有一个这样的javascript数组

   var open_chats = [];
   open_chats.push({
    "chatid": 'dfsfsdfsdf',
    "data": 'adfsdf'
   });

我需要检查此数组中是否存在项目,我正在使用这样的东西。

    if ($.inArray('dfsfsdfsdf', open_chats) !== -1){
    alert('contains');
    }

除了这似乎不起作用。我找不到适用于此数组的东西。谁能帮忙?

您的代码正在检查数组中是否'dfsfsdfsdf',而不是属性为 chatid 的对象是否具有 'dfsfsdfsdf' 作为其值。

使用本机 JavaScript 数组方法:

var hasMatch = open_chats.some(function(chat) {
    return chat.chatid === 'dfsfsdfsdf';
});
if (hasMatch) {
    alert('contains');
}

由于数组中有对象而不是字符串,我建议使用 jQuery 的 grep 方法:

var result = $.grep( open_chats, function( data ){ return data.chatid == 'dfsfsdfsdf'; });
if( result.length ) {
    alert('contains');
}