繁体   English   中英

Python中的列表=> Javascript翻译

[英]Lists in Python => Javascript Translation

for i in [name, matches_total, matches_won, matches_lost]:
    doSomething(i)

我尝试为JS执行此操作,但没有成功。 基本上,我希望它对每个变量都做任何事情。 我该如何使用JS?

我的尝试:

for (i in [name, matches_total, matches_won, matches_lost]){
    doSomething(i);
}

JavaScript的in运算符不完全相同。 如果您在支持forEach的环境中,则它的风格就比较接近(除了为循环定义一个内部匿名函数外,有点像Python lambda

[name, matches_total, matches_won, matches_lost].forEach(function(i) {
    doSomething(i);
});

在这种情况下(在每个列表项上调用单个函数的情况下),您可以通过一种在语法上我觉得很好的方式简化此过程:

[name, matches_total, matches_won, matches_lost].forEach(doSomething);
for (var i = 0; i < list.length; ++i) {
    doSomething(list[i]);
}

for循环有两种,一种是为对象设计的for-in循环,另一种是for (;;)的三态for循环。 不建议在数组上使用for-in ,因为它也会遍历其原型链。

var my_array = [name, matches_total, matches_won, matches_lost]

for (var i in my_array){
    doSomething(my_array[i]);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM