javascript - 当 String === String 时,Javascript 循环不返回 true
问题描述
当循环遍历数组以查找数组是否包含我要查找的单词时,如果我 console.log out 正在比较的内容,则循环始终返回“false”,我可以清楚地看到我正在查找的单词( collectionNameLookingFor) 在数组 (collectionNameArray) 中,所以它应该返回 true。
function checkCollectionNames(arrayOfCollections, collectionName) {
for (let i = 0; i < arrayofCollections.length; i++) {
if (arrayOfCollections[i] === collectionName) {
return true;
}
}
return false;
}
function saveContentToDb(req, res) {
const db = getDb();
const pageDetails = req.body;
let saveType;
db.db(pageDetails.databaseName).listCollections().toArray((error, collections) => {
if (error) {
throw error;
} else {
collections.map(collection => (collection.name)).forEach(collectionNameArray => {
const collectionNameLookingFor = req.body.page;
const check = checkCollectionNames(collectionNameArray, collectionNameLookingFor);
console.log('===========Looking to see if it is true or false==========');
console.log(check);
console.log(`Name of collection in Database: ${collectionNameArray} ::: ${collectionNameLookingFor}`);
console.log('==========================================================');
if (check === true) {
saveType = 'updated';
console.log(`saveType = ${saveType}`);
} else {
saveType = 'created';
console.log(`saveType = ${saveType}`);
}
});
}
});
}
解决方案
您可能需要检查,因为这是您在旁边而不是本身collectionName
移交的参数。arrayOfCollections
array
function checkCollectionNames(arrayOfCollections, collectionName) {
for (let i = 0; i < arrayOfCollections.length; i++) {
if (arrayOfCollections[i] === collectionName) {
return true;
}
}
return false;
}
精简版:
function checkCollectionNames(arrayOfCollections, collectionName) {
return arrayOfCollections.includes(collectionName);
}
推荐阅读
- c# - 在哪里打电话所以我可以管理异常?
- php - 在 PHP 会话中存储大型网站菜单是个好主意吗?
- javascript - 在 Typescript / Javascript 中更新嵌套对象中的字段
- php - 将两个数组组合成一个字符串
- python - Python:检查嵌套字典中的特定键,如果匹配则返回所有先前的键
- r - 可变长度在 R 中使用 lm 不同
- java - 是否可以基于 if 语句进行循环?
- eclipse - eclipse 拖动编辑器选项卡以重新排列它们
- actionscript-3 - 嵌入字体不显示文本 (as3)
- reactjs - 我需要一个 HTTP 服务器(例如 Express、Nginx 等)来在 Heroku 上响应应用程序吗?