【问题标题】:Translate python conditional to javascript -- control flow将 python 条件转换为 javascript -- 控制流
【发布时间】:2018-06-07 13:48:45
【问题描述】:

如何在 JavaScript 中做到这一点?当它在big_list 中点击words 时,它应该打印'Found'

big_list = ['this', 'is', 'a', 'long', 'list', 'of' 'words']

needle = ['words', 'to', 'find']

for i in big_list:
    if i in needle:
        print('Found')
    else:
        print('Not Found')

我知道一般的 if/else 结构,但不确定语法:

if (big_list in needle) {
  console.log('print some stuff')
} else {
  console.log('print some other stuff')
}

【问题讨论】:

    标签: javascript python arrays list


    【解决方案1】:

    您可以将includes 函数与for 循环一起使用,如下所示:

    for (let i = 0; i < big_list.length; i++)
    {
        if (needle.includes(big_list[i])) console.log("Found");
        else console.log("Not found");
    }
    

    或者使用forEach:

    big_list.forEach(function(e) { 
         if (needle.includes(e)) console.log("Found");
         else console.log("Not found");
    });
    

    【讨论】:

      【解决方案2】:

      您几乎已经掌握了它,但有几点需要注意。首先,in 关键字在 javascript 中的工作方式与在 python 中的不同。在 python 中,它可以用来检查一个项目是否是集合的成员,但在 javascript 中,它会检查该项目是否是一个对象的 key。所以:

      "foo" in {foo: "bar"} // True
      

      但是

      "foo" in ["foo", "bar"] // False
      

      因为在第二种情况下,虽然"foo" 是数组的成员,但in 关键字正在寻找它作为键。在这些方面:

      "0" in ["foo", "bar"] // True
      

      由于"0"是数组的键(即指向第一项的键)

      除此之外,您的代码无需太多更改即可适应 javascript。只需使用 varconstlet 声明您的变量,在您的 if 中使用大括号,然后用它们的 javascript 等效项替换调用:

      /*
      
      # Python Code:
      big_list = ['this', 'is', 'a', 'long', 'list', 'of', 'words']
      
      needle = ['words', 'to', 'find']
      
      for i in big_list:
          if i in needle:
              print('Found')
          else:
              print('Not Found')
      
      */
      
      // Now in javascript:
      
      const big_list = ['this', 'is', 'a', 'long', 'list', 'of', 'words']
      const needle = ['words', 'to', 'find']
      
      for (let i of big_list) {
        if (needle.includes(i)) {
          console.log('Found')
        } else {
          console.log('Not Found')
        }
      }

      【讨论】:

        猜你喜欢
        • 2017-05-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-30
        • 2018-07-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多