表达式周围的方括号是什么意思,例如`var x = a + [b]`? [英] What do square brackets around an expression mean, e.g. `var x = a + [b]`?

查看:26
本文介绍了表达式周围的方括号是什么意思,例如`var x = a + [b]`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们从一家机构收到了一些看起来有问题但有效的 JavaScript.

We have received some JavaScript from an agency that looks wrong, but works.

出于某种原因,他们在变量周围添加了方括号([, ]),如下所示:

For some reason they are adding square brackets ([, ]) around variables, like this:

var some_variable = 'to=' + [other_variable];

这行得通,但方括号似乎完全是多余的.

This works, but the square brackets seem completely superfluous.

使用这种语法是有目的还是技术上不正确,但被浏览器忽略了?

Is there a purpose of using this syntax or is it technically incorrect, but ignored by the browser?

推荐答案

方括号表示新数组.

var ar=new Array("a","b");
var ar=["a","b"]; //Equal to the syntax above

在那种情况下,是否使用方括号没有区别,因为如果它是一个数组,它会被转换为字符串,但是如果删除方括号,它需要的时间更少,因为它不必构建一个新数组并进行转换它但它适用于一个简单的字符串.

in that situation there's no difference if you use square brackets or not because if it's an array it is converted to string, but if you delete the brackets it takes less time because it doesn't have to build a new array and convert it but it works with a simple string.

这篇关于表达式周围的方括号是什么意思,例如`var x = a + [b]`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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