【问题标题】:Having problems using nested for loops使用嵌套 for 循环时遇到问题
【发布时间】:2017-03-03 13:33:23
【问题描述】:

我很难弄清楚这一点。我想将 2 个数组的内容相互比较。如果它们是 === 我想运行 if 语句,否则运行 else 语句。到目前为止,这有效,但 if 和 else 发生了,而不仅仅是其中的 1 个。

<% for (var i = 0; i < match.interests.length; i++) { %>
    <% for (var j = 0; j < user.interests.length; j++) { %>
        <% if (match.interests[i] === user.interests[j]) { %>
            <li class="tag positive"><%= match.interests[i] %></li>
        <% } else {%>
            <li class="tag"><%= match.interests[i] %></li>
        <% } %>
    <% } %>
<% } %>

【问题讨论】:

  • 你的意思是两者都发生,而不仅仅是一个?您是说两者都发生在嵌套循环的同一迭代中(这应该是不可能的)?
  • 让我们说 Array a = ['Code', 'JS'] Array b = ['Code'] 这个脚本现在的结果是:Code Code JS 而不是 Code JS @DylanHamilton
  • 在 if 和 else 语句中使用 break
  • 您应该尝试在 if 语句之前的行中添加 console.log。记录 i 和 j。这应该可以帮助您确定每个循环运行了多少次。
  • 在某些时候,您会将“某些值”与未定义进行比较,因为数组的长度不同。

标签: javascript node.js express for-loop ejs


【解决方案1】:

你的平等检查很好,问题来了,因为你总是在 else 语句上记录一些东西。

console.clear();

const match = {
  interests: [
    'Code',
    'JS'
  ],
};

const user = {
  interests: [
    'Code',
    'Apples',
    'Skiing'
  ],
};

const output = [];

for (let i = 0; i < match.interests.length; i++) {
  for (let j = 0; j < user.interests.length; j++) {
    console.log('loop')
    if (match.interests[i] === user.interests[j]) {
      console.log('MATCH');
      output.push(match.interests[i]);
    } else {
      console.log('DOESN\'T MATCH');
      output.push(match.interests[i]);
    }
  }
}

console.log(output);

查看以下代码的输出,你需要决定你想要什么输出并相应地调整你的循环

【讨论】:

    猜你喜欢
    • 2016-06-06
    • 1970-01-01
    • 1970-01-01
    • 2020-06-21
    • 1970-01-01
    • 1970-01-01
    • 2012-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多