javascript - 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)
};
});
解决方案
你的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)
};
});
推荐阅读
- macros - rustc --pretty expand 在解析外部块内的宏扩展时使用了我所有的 RAM
- node.js - NodeJS MSSQL REST 连接关闭错误
- symfony - 在 Symfony 4 页面中找不到路由
- python - 需要从模板中的 django 获取实例 id
- r - 如何在单位正方形上多次进行 100 个点的 Voronoi 镶嵌
- c# - 如何在 .NET Core 的主布局视图中呈现特定控制器的操作?
- javascript - 是否有在样式组件中使用 mixin 的替代解决方案?
- c - 在 libtomcrypt 中比较处理器性能时出现异常结果
- javascript - 通过js获取参数设置隐藏字段的值
- node.js - 平面 JSON 到层次结构 JSON