String === String时,Javascript循环不返回true

问题描述 投票:0回答:1

当循环遍历数组以查找数组是否包含我正在寻找的单词时,循环总是返回'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}`);
        }
      });
    }
  });
}
javascript arrays node.js mongodb
1个回答
0
投票

你可能需要检查collectionName,因为这是你移交的参数,除了arrayOfCollections,而不是array本身。

function checkCollectionNames(arrayOfCollections, collectionName) {
    for (let i = 0; i < arrayOfCollections.length; i++) {
        if (arrayOfCollections[i] === collectionName) {
            return true;
        }
    }
    return false;
}

Short Version:

function checkCollectionNames(arrayOfCollections, collectionName) {
    return arrayOfCollections.includes(collectionName);
}
© www.soinside.com 2019 - 2024. All rights reserved.