定义多个变量的简便方法

时间:2015-06-29 07:03:25

标签: javascript

页面上大约有35个变量以空白开头。每个变量用于不同的目的。

var a = '',
    b = '',
    c = '';

是否有更短的方式来编写这些变量?

2 个答案:

答案 0 :(得分:2)

像这样:

var a = b = c = '',

<强> Working Demo

答案 1 :(得分:1)

每当你看到自己重复某些事情时,你想要寻找更好的方法:

在这种情况下,有一些叫做变量数组的东西。通常,您使用带循环的数组来实现重复性任务。

数组是可以通过索引访问的变量列表。好像你有一个名为a0,a1,a2,a2等的变量......如果能够通过所有变量而不必明确地输入每个变量,那么会不会很棒?

这就是数组和循环一起工作的方式:

var a = new Array(); // declare the array; "a" is the name of your array here
a[0] = ""; // this is how you assign the first index in the array
a[1] = ""; // second, etc

// now stop doing this manually and do the code below

// this is how you loop 30 times assigning each variable in the array to an empty string
for (var i=0; i < 30; i++) {
  a[i] = "";
}

console.log("This is the array: ", a);

PS:有更好的方法来解决你的问题,但这个是最直接的=)

相关问题