【发布时间】:2020-07-26 13:39:37
【问题描述】:
由于某种原因,我无法正确过滤我的列表,因为 name.includes(line) 始终是 false。
http
.createServer((req, res) => {
// .. Here you can create your data response in a JSON format
let body = [];
req
.on('error', (err) => {
console.error(err);
})
.on('data', (chunk) => {
body.push(chunk);
})
.on('end', () => {
body = Buffer.concat(body).toString();
console.log(req);
const list = JSON.parse(JSON.stringify(data)).filter(({ name }) => {
console.log(
name.toLowerCase(),
body.toLowerCase(),
name.toLowerCase().includes(body.toLowerCase())
);
console.log(name.toLowerCase().includes('damage'));
return name.toLowerCase().includes(body.toLowerCase());
});
console.log(list);
handleResponse(req, res, data);
});
})
.listen(port);
结果:
"damage"
damage reverse oil conditioner "damage" false
true
volume advance conditioner "damage" false
false
volume advance shampoo "damage" false
false
damage reverse oil shampoo "damage" false
true
color sustain pro "damage" false
false
damage reverse hair serum "damage" false
true
damage reverse restorative hair treatment "damage" false
true
[]
我不知道为什么它显示false。为了检查我的理智,我检查了浏览器中的第一行并显示true。
提前致谢。
【问题讨论】:
-
它是case sensitive。还有为什么你的
"damage"周围有引号? -
但这也行不通
name.toLowerCase().includes(body) -
如您所见,
"Damage Reverse Oil Conditioner".toLowerCase().includes("damage") === true。您的某些字符串不是您认为的那样(例如,请注意上面提到的引号),根本不是字符串(您调用的不是String.prototype.includes,或者传递的不是字符串,并且可能会发生变异),或者你之前错过了toLowerCase。 -
你能把
data的具体内容和它的类型包括进来吗? -
我可能找到了原因,我的身体由于某种原因无法匹配
body = Buffer.concat(body).toString();,但name.toLowerCase().includes('damage')工作正常。它来自 NodeJS 服务器上的响应
标签: javascript node.js string filter