[英]Javascript For Loop with 2 sets of parenthesis (round brackets) - FOR ()()
I just got a code from somewhere, which I trying to understand.我刚从某个地方得到一个代码,我试图理解它。 But I stuck on a place which I can not understand.
但是我卡在了一个我无法理解的地方。 Javascript code is as below:
Javascript 代码如下:
for(t_var=0,n_var=i_var.length; t_var<n_var; t_var++)
(e_var=i_var[t_var])[0]
.removeEventListener(e_var[1],d_var)
It is a single line javascript for loop.它是单行 javascript for loop。 I can not understand the use of 2nd set of round bracket ie contains (e_var=i_var[t_var]) .
我无法理解第二组圆括号的使用,即包含(e_var=i_var[t_var]) 。 I think it might be creating some sort of array because [0] after 2nd set of parenthesis shows it as an array.
我认为它可能正在创建某种数组,因为在第二组括号之后的[0]将其显示为数组。 But I am not sure what is its exact use?
但我不确定它的确切用途是什么?
Can anyone help with it please?有人可以帮忙吗?
Regards问候
You could rewrite the code in the following manner to make it better understandable:您可以按以下方式重写代码以使其更易于理解:
for(t_var=0,n_var=i_var.length; t_var<n_var; t_var++)(e_var=i_var[t_var])[0].removeEventListener(e_var[1], d_var);
// on multiple lines
for (t_var = 0, n_var = i_var.length; t_var < n_var; t_var++)
(e_var = i_var[t_var])[0].removeEventListener(e_var[1], d_var);
// using a for-loop with curly brackets
for (t_var = 0, n_var = i_var.length; t_var < n_var; t_var++) {
(e_var = i_var[t_var])[0].removeEventListener(e_var[1], d_var);
}
// splitting assignment and event listener removal
for (t_var = 0, n_var = i_var.length; t_var < n_var; t_var++) {
e_var = i_var[t_var];
e_var[0].removeEventListener(e_var[1], d_var);
// ^ the expression `(e_var = i_var[t_var])` returns the value assigned to `e_var`
}
// removal of array length caching to make the loop more readable
for (t_var = 0; t_var < i_var.length; t_var++) {
e_var = i_var[t_var];
e_var[0].removeEventListener(e_var[1], d_var);
}
// more descriptive variable names
for (index = 0; index < array.length; index++) {
arrayElement = array[index];
arrayElement[0].removeEventListener(arrayElement[1], eventListener);
}
// using destructuring assignment
for (index = 0; index < array.length; index++) {
arrayElement = array[index];
const [htmlElement, eventType] = arrayElement;
htmlElement.removeEventListener(eventType, eventListener);
}
// using for...of instead of standard for-loop
for (const [htmlElement, eventType] of array) {
htmlElement.removeEventListener(eventType, eventListener);
}
Note that your example doesn't use var
, let
, or const
to define the variables.请注意,您的示例不使用
var
、 let
或const
来定义变量。 The changes above doesn't use those either except for the new variables introduced by me.除了我介绍的新变量之外,上面的更改也没有使用这些更改。 Normally variables should always be defined using 1 of the 3 keywords (preferably
let
or const
), otherwise the variables are global.通常,变量应始终使用 3 个关键字中的一个(最好是
let
或const
)来定义,否则变量是全局的。 Global variables often lead to unexpected behaviour, resulting in bugs.全局变量通常会导致意外行为,从而导致错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.