Javascript If List Cotains?



我不知道如何检查我的列表是否包含元素。

 for (x in chatBoxes) {
            chatboxtitle = chatBoxes[x];
            if (chatboxtitle==obj[ i ].from) {
            //alert(obj[ i ].from + " YES !");
            } else {
            //alert(obj[ i ].from + " NOPE !");
            }
            };

问题它是如何工作的?或者如何将其编码为如果聊天框包含obj[i]。从那时起是否则否因为目前只有当聊天框列表中有一个元素时,它才有效。。。如果什么都没有,则什么都没有发生

如果chatBoxes是一个对象,您需要使用标志来确定该对象是否包含所述值,然后在循环之后,您需要执行取决于包含标志的操作。

var contains = false;
for (x in chatBoxes) {
    if (chatBoxes[x] == obj[i].from) {
        contains = true;
        break;
    }
};
if (contains) {
    alert(obj[i].from + " YES !");
} else {
    alert(obj[i].from + " NOPE !");
}

但如果chatBoxes是阵列

if(chatBoxes.indexOf(obj[i].from) > -1){
    alert(obj[i].from + " YES !");
} else {
    alert(obj[i].from + " NOPE !");
}

假设chatBoxes是一个数组,则使用indexOf()

if (chatBoxes.indexOf(obj[ i ].from) > -1)

最新更新