首页 > 解决方案 > 你能帮忙看看控制台日志吗?

问题描述

我需要计算 X 和 Y,但我的控制台日志有效,如果匹配 [i].includes(something) == "true" 可能有问题

    var input = "10W5N2S6E";
var matches = input.split(/(?<=[A-Z])(?=\d)/);
for (let i = 0; i < matches.length; i++) {
  let x = 0;
  let y = 0;
  if (matches[i].includes("w") == "true") {
    x = x - matches[i];
    console.log(x);
  }
  if (matches[i].includes("e") == "true") {
    x = x + matches[i];
    console.log(x);
  }
  if (matches[i].includes("n") == "true") {
    y = y + matches[i];
    console.log(y);
  }
  if (matches[i].includes("s") == "true") {
    y = y - matches[i];
    console.log(y);
  }
}

标签: javascript

解决方案


您需要使用,toLowerCase()因为includes()它区分大小写。

此外,无需比较,includes() == "true"因为它返回一个布尔值并且对于 if 条件(它将根据该布尔条件执行下一个块语句)就足够了

var input = "10W5N2S6E";
var matches = input.split(/(?<=[A-Z])(?=\d)/);
for (let i = 0; i < matches.length; i++) {
  const match = matches[i].toLowerCase();
  let x = 0;
  let y = 0;
  if (match.includes("w")) {
    x = x - matches[i];
    console.log(x);
  }
  if (match.includes("e")) {
    x = x + matches[i];
    console.log(x);
  }
  if (match.includes("n")) {
    y = y + matches[i];
    console.log(y);
  }
  if (match.includes("s")) {
    y = y - matches[i];
    console.log(y);
  }
}


推荐阅读