函数中的括号Javascript [英] Brackets in Functions Javascript

查看:181
本文介绍了函数中的括号Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解Javascript中for循环和if语句中括号的用法。我已经看到JavaScript中的语法,其中有括号和没有。我被告知通常应该使用括号。有人可以清楚地解释什么时候我们应该使用for和if循环括号吗?

pre $函数范围(upto){
var result = [];
for(var i = 0; i <= upto; i ++)
result [i] = i;
返回结果;
}
console.log(range(15));

这个结果会是

 [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] 

这是与括号:

 函数范围(upto){
var result = [];
for(var i = 0; i <= upto; i ++){
result [i] = i;
};
返回结果;

}
console.log(range(15));


解决方案

可以省略括号当 for 循环适用于唯一语句。



如果您希望将其应用于更多语句,则必须使用它。更确切地说,循环的总是适用于一个语句,但是方括号内是一个语句块。



添加方括号时,只有一个语句,不能破坏代码往往使其更具可读性。事实上,大多数编码器不会在没有括号的循环的开头中进入下一行。我个人替换



 为(VAR I = 0; I< =高达;我++)
结果[I ] = i;



 <$ (var i = 0; i <= upto; i ++)result [i] = i; 

  for(var i = 0; i <= upto; i ++){
result [i] = i;
}


I am having trouble understanding the usage of brackets in "for" loops and "if" statements in Javascript. I have seen syntax in Javascript where there is brackets and where there isn't. I was told that generally one should use the brackets. Can someone clearly explain when we should use brackets for "for" and "if" loops?

function range(upto) {
  var result = [];
  for (var i = 0; i <= upto; i++)
    result[i] = i;
  return result;
}
console.log(range(15));

The result of this would be

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

This is vs. the brackets:

function range(upto) {
  var result = [];
  for (var i = 0; i <= upto; i++) {
    result[i] = i;
  };
    return result;

}
console.log(range(15));

解决方案

You can omit the brackets when the for loop applies to a unique statement.

You must use it if you want it to apply to more statements. To be more precise, the for loop always apply to a statement but the brackets build a block which is a statement.

Adding the brackets, when there is only one statement, can't break the code and often makes it more readable. In fact most coders won't go to the next line in an opening for loop without brackets. I personally would replace

for (var i = 0; i <= upto; i++)
    result[i] = i;

with

for (var i = 0; i <= upto; i++) result[i] = i;

or

for (var i = 0; i <= upto; i++) {
    result[i] = i;
}

这篇关于函数中的括号Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆