“use strict”:为多个变量赋值

时间:2022-11-28 15:12:31

Is there any other way in "use strict"; javascript to initialize a value to multiple variables? Because doing this:

“严格使用”还有其他办法吗? javascript将值初始化为多个变量?因为这样做:

var x = y = 14;

will cause error: Uncaught ReferenceError: y is not defined

将导致错误:未捕获的ReferenceError:y未定义

Got my reference here:

在这里得到我的参考:

Set multiple variables to the same value in Javascript

在Javascript中将多个变量设置为相同的值

2 个解决方案

#1


There are side affects to var x = y = 14; which is why it's not allowed in strict mode. Namely, y becomes a global variable.

对var x = y = 14有副作用;这就是严格模式下不允许的原因。即,y成为全局变量。

When you say

当你说

var x = y = 14;

It is equivalent to

它相当于

var x;
y = 14;
x = y;

Where x is declared as a local variable and y is created as a global variable.

其中x被声明为局部变量,y被创建为全局变量。

For more information on using var to declare variables see this question. Additionally, it may be worth noting that ES6 is introducing the keyword let that enables block level scoping in contrast to function level scoping that exists with var.

有关使用var声明变量的更多信息,请参阅此问题。此外,值得注意的是ES6引入了关键字let,它启用了块级别范围,与var中存在的功能级别范围相反。

Finally, if you want to assign both variables a value, any of the following would do

最后,如果要为两个变量分配值,则可以执行以下任何操作

var x, y;
x = y = 14;

var x = 14,
    y = x;

var x = 14,
    y = 14;

var x = 14;
var y = 14;

#2


Yup - don't mix declarations and assignments.

是的 - 不要混合声明和作业。

var x, y;
x = y = 14;

#1


There are side affects to var x = y = 14; which is why it's not allowed in strict mode. Namely, y becomes a global variable.

对var x = y = 14有副作用;这就是严格模式下不允许的原因。即,y成为全局变量。

When you say

当你说

var x = y = 14;

It is equivalent to

它相当于

var x;
y = 14;
x = y;

Where x is declared as a local variable and y is created as a global variable.

其中x被声明为局部变量,y被创建为全局变量。

For more information on using var to declare variables see this question. Additionally, it may be worth noting that ES6 is introducing the keyword let that enables block level scoping in contrast to function level scoping that exists with var.

有关使用var声明变量的更多信息,请参阅此问题。此外,值得注意的是ES6引入了关键字let,它启用了块级别范围,与var中存在的功能级别范围相反。

Finally, if you want to assign both variables a value, any of the following would do

最后,如果要为两个变量分配值,则可以执行以下任何操作

var x, y;
x = y = 14;

var x = 14,
    y = x;

var x = 14,
    y = 14;

var x = 14;
var y = 14;

#2


Yup - don't mix declarations and assignments.

是的 - 不要混合声明和作业。

var x, y;
x = y = 14;