我已经使用library(dplyr)
df <- tibble(List = list(c("47", "39", "1"), c("11","11"), c("1","2"))) %>%
rowwise() %>%
mutate(SumList = sum(as.numeric(List)))
和fs.readFile()
来读取'words_alpha.txt'。该文件可从以下位置公开获得:https://raw.githubusercontent.com/dwyl/english-words/master/words_alpha.txt
即使查询fs.readFileSync()
与test
文件行数组中的单词匹配,JSON仍始终使用以下JavaScript代码用words_alpha.txt
进行响应:
{ includes: false, indexFound: false, found: undefined, forFound: false }
为什么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)
都找不到任何匹配项?但是'words_alpha.txt'for (i in words) if (words[i] === test)
可以用words
一次登录,但需要几秒钟才能完成。
答案 0 :(得分:2)
问题在于,您使用的文件具有Windows样式行结尾(以字符表示的CR LF或\r\n
),并且您正在按Unix样式行结尾(LF或\n
)分割,这会产生一个错误的单词数组:
const stringOfWords = "apple\r\nbroccoli\r\ncarrot"; //windows line endings
console.log(stringOfWords)
const words = stringOfWords.split("\n");
console.log(words);
console.log(words.includes("apple"))
或者您只能按Windows行尾拆分,但是您冒着代码不适用于Unix行尾的风险:
const stringOfWords = "apple\r\nbroccoli\r\ncarrot"; //windows line endings
console.log(stringOfWords)
const words = stringOfWords.split("\r\n");
console.log(words);
console.log(words.includes("apple"))
或者您也可以将文件转换为Unix文件结尾,并且您的代码将保持不变:
const stringOfWords = "apple\nbroccoli\ncarrot"; //unix line endings
console.log(stringOfWords)
const words = stringOfWords.split("\n");
console.log(words);
console.log(words.includes("apple"))
或者您可以修剪单词以除去空格,从而能够处理任一行的结尾,但是对于大文件而言,这可能是繁重的操作:
const stringOfWords = "apple\r\nbroccoli\r\ncarrot"; //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 = "apple\r\nbroccoli\r\ncarrot"; //windows line endings
console.log(stringOfWords)
const words = stringOfWords.split(/\r?\n/);
console.log(words);
console.log(words.includes("apple"))