在JavaScript中,可以像这样声明多个变量:
var variable1 = "Hello, World!";
var variable2 = "Testing...";
var variable3 = 42;
...或者像这样:
var variable1 = "Hello, World!",
variable2 = "Testing...",
variable3 = 42;
一种方法比另一种更好/更快吗?
在JavaScript中,可以像这样声明多个变量:
var variable1 = "Hello, World!";
var variable2 = "Testing...";
var variable3 = 42;
...或者像这样:
var variable1 = "Hello, World!",
variable2 = "Testing...",
variable3 = 42;
一种方法比另一种更好/更快吗?
当前回答
var variable1 = "Hello, World!";
var variable2 = "Testing...";
var variable3 = 42;
比:
var variable1 = "Hello, World!",
variable2 = "Testing...",
variable3 = 42;
但它们做的事情是一样的。
其他回答
使用ES6解构赋值:它会将数组中的值或对象中的属性解压缩到不同的变量中。
Let [variable1, variable2, variable3] = ["Hello, World!", "Testing…",42]; console.log (variable1);//你好,世界! 如上所述console.log(的操作);/ /测试…… console.log (variable3);/ / 42
我们可以使用所有的方法,没有必要只选择其中一种。应用不同的方法可以使代码更易于阅读。
我将展示我Vue.js 3项目中的一个真实例子:
示例1
const [store, route] = [useStore(), useRoute()]
const
showAlert = computed(() => store.getters['utils/show']),
userIsLogged = computed(() => store.getters['auth/userIsLogged']),
albumTitle = computed(() => store.getters['albums/title']);
示例2
const
store = useStore(),
username = ref(''),
website = ref(''),
about = ref('');
const
isAppFirstRender = computed(() => store.getters['utils/isAppFirstRender']),
showToast = ref(false);
正如你在上面看到的,我们可以有一小块变量声明。没有必要声明大块。假设我有12个变量,我可以以一种有意义或看起来更容易阅读的方式将它们分组,而不需要冗长:
const
numberOne = 5,
numberTwo = 10,
numberThree = 15;
const
stringOne = 'asd',
stringTwo = 'asd2',
stringThree = 'asd3';
let [one, two, three] = [1,2,3]
当然,每个人都有自己的风格。这是我个人的偏好,混合使用所有方法。
我个人不喜欢冗长。我喜欢有它所需要的而不是更多的代码。
第二种方法的主要问题是,到目前为止还没有IDE支持这种风格。 你不能折叠这些结构。
ECMAScript 2015引入了解构赋值,效果非常好:
[a, b] = [1, 2]
A等于1 b等于2。
这样做的时候可读性更强:
var hey = 23;
var hi = 3;
var howdy 4;
但是这种方法占用的空间和代码行数更少:
var hey=23,hi=3,howdy=4;
它是节省空间的理想选择,但是让JavaScript压缩器为您处理它。