【发布时间】:2019-03-13 14:12:39
【问题描述】:
当循环遍历数组以查找数组是否包含我要查找的单词时,如果我 console.log out 正在比较的内容,则循环始终返回“false”,我可以清楚地看到单词 I am寻找 (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}`);
}
});
}
});
}
【问题讨论】:
-
checkCollectionNames有一个名为arrayOfCollections的第一个参数,但您在函数本身中将其简称为array。这些肯定应该匹配吗? -
您是否考虑过使用
Array.prototype.includes方法而不是自己编写? -
应该是
collectionName而不是page? -
您能否检查一下数组的元素是字符串还是对象。使用“console.log(typeof array[i])”。因为您可以使用 new String(...) 以对象的形式创建字符串。
-
如果数组元素是对象,那么使用 "==" 而不是 "===" 就可以了。
标签: javascript arrays node.js mongodb