首页 > 解决方案 > If statement returns undefined when checking if an array doesn't contain a word

问题描述

I'm trying to log each name in the array except for the users, _id, etc. Doing if(!word === "users") works and logs the user entry as I would expect. I'm probably overlooking something trivial and apologize in advance. Thank you.

let arr = ["noun","nounoffensive","nounvulgar","adjective","verb","verbinformal","conjunction","exclamation","users","_id","word","createdAt","updatedAt","__v"]

arr.forEach((word)=>{
    if(!word === "users" || "_id" || "word" || "createdAt" || "updatedAt"){
        console.log(word)
    };
});

标签: javascriptarraysif-statement

解决方案


你的if说法不正确。您缺少word ===其他比较,并且!应该在那里进行整个表达。

let arr = ["noun","nounoffensive","nounvulgar","adjective","verb","verbinformal","conjunction","exclamation","users","_id","word","createdAt","updatedAt","__v"]

arr.forEach((word)=>{
    if(!(word === "users" || word === "_id" || word === "word" || word === "createdAt" || word === "updatedAt")){
        console.log(word)
    };
});

另一种方法也可以是创建一个数组,例如,let notInArray = ["users", "_id", "word", "createdAt", "updatedAt"];其中包含您要排除的单词:

let arr = ["noun","nounoffensive","nounvulgar","adjective","verb","verbinformal","conjunction","exclamation","users","_id","word","createdAt","updatedAt","__v"]

let notInArray = ["users", "_id", "word", "createdAt", "updatedAt"];
arr.forEach((word)=>{
  if(notInArray.indexOf(word) === -1){
    console.log(word)
  };
});


推荐阅读