【问题标题】:NodeJs String.inculdes() does not work as expectedNodeJs String.inculdes() 无法按预期工作
【发布时间】: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


【解决方案1】:

String.prototype.includes() 区分大小写listed here

【讨论】:

  • 但这也行不通name.toLowerCase().includes(body)
【解决方案2】:

这是我解决此问题的工作。问题是因为Buffer.concat(body).toString()的body转换不正确,所以我改成这样:

const bodyLine = JSON.stringify(body);
body = bodyLine.substring(3, bodyLine.length - 3);

并改变身体创造自己: 而不是

let body = [];
    req
      .on('error', (err) => {
        console.error(err);
      })
      .on('data', (chunk) => {
        body.push(chunk);
      })

我用字符串替换数组并连接块

let body = '';
    req
      .on('error', (err) => {
        console.error(err);
      })
      .on('data', (chunk) => {
        body += chunk.toString();
      })

【讨论】:

    猜你喜欢
    • 2017-05-07
    • 1970-01-01
    • 1970-01-01
    • 2019-07-03
    • 1970-01-01
    • 1970-01-01
    • 2013-12-23
    • 2014-12-09
    • 2016-01-13
    相关资源
    最近更新 更多