array.includes()总是false,array.indexof()总是-1 and array.find()



我已经使用 fs.readFile()fs.readFileSync()读取'words_alpha.txt'。该文件可在以下公开信息:https://raw.githubusercontent.com/dwyl/english-words/master/words_alpha.txt

即使查询testwords_alpha.txt文件行数组上匹配一个单词,JSON始终使用{ includes: false, indexFound: false, found: undefined, forFound: false }响应以下JavaScript代码:

var express = require('express');
var router = express.Router();
var fs = require('fs');
router.get('/test_validation', function(req, res, next) {
  const { test } = req.query;
  fs.readFile('words_alpha.txt', function(err, data) {
    const words = data.toString().split('n');
    const includes = words.includes(test);
    const indexFound = words.indexOf(test) > -1;
    const found = words.find(word => word === test);
    let forFound = false;
    for (i in words) {
      if (words[i] === test) {
        forFound = true;
        break;
      }
    }
    res.json({ includes, indexFound, found, forFound });
  });
});

为什么words.includes(test)words.indexOf(test)words.find(word => word === test)找不到任何匹配,甚至使用for (i in words) if (words[i] === test)?但是" words_alpha.txt" words可以用for (i in words) console.log(words[i])一个一个一个一个,但需要几秒钟才能完成。

问题是您使用的文件具有Windows样式行末尾(CR LF或rn表示为字符),并且您通过Unix样式线路结束(LF或n)分裂,可产生一个单词不正确:

const stringOfWords = "applernbroccolirncarrot"; //windows line endings
console.log(stringOfWords)
const words = stringOfWords.split("n");
console.log(words);
console.log(words.includes("apple"))

,或者您只能通过Windows行末尾分开,但您可能会冒着代码不适用于UNIX线路结尾的风险:

const stringOfWords = "applernbroccolirncarrot"; //windows line endings
console.log(stringOfWords)
const words = stringOfWords.split("rn");
console.log(words);
console.log(words.includes("apple"))

或者您可以将文件转换为Unix文件末尾,而您的代码将无需更改:

const stringOfWords = "applenbroccolincarrot"; //unix line endings
console.log(stringOfWords)
const words = stringOfWords.split("n");
console.log(words);
console.log(words.includes("apple"))

或者您可以修剪单词以删除空格,从而能够处理任何一条线结尾,但这可能是大型文件的潜在沉重操作:

const stringOfWords = "applernbroccolirncarrot"; //windows line endings
console.log(stringOfWords)
const words = stringOfWords.split("n")
  .map(word => word.trim());
console.log(words);
console.log(words.includes("apple"))

,也可以通过Windows或Unix行末尾的正则表达式分开:

const stringOfWords = "applernbroccolirncarrot"; //windows line endings
console.log(stringOfWords)
const words = stringOfWords.split(/r?n/);
console.log(words);
console.log(words.includes("apple"))

最新更新