var x, y = 'foo';这能实现吗? [英] var x, y = 'foo'; Can this be accomplished?

查看:24
本文介绍了var x, y = 'foo';这能实现吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

既然可以这样做:

var x = 'foo', y = 'foo';

这也有可能吗?

var x, y = 'foo';

我试过了,但是 x 变得未定义.

I tried it, however x becomes undefined.

我知道这似乎是一个愚蠢或多余的问题,但如果我对某些事情感到好奇,为什么不问呢?此外,您可能会想知道为什么我需要两个变量,在作用域中是相同的.这不是问题的重点.我只是好奇.

I know this may seem like a silly or redundant question, but if I'm curious about something, why not ask? Also you will probably wonder why I would need two variables equal to the same thing in scope. That is not the point of the question. I'm just curious.

推荐答案

您需要两个单独的语句才能获得完全相同的语义.

You need two separate statements to get the exact same semantics.

var x, y; x = y = 'foo';
// or
var x = 'foo'; var y = x;
// or
var y; var x = y = 'foo';

其他用户建议的解决方案等效,因为它没有将 var 应用于 y.如果有一个全局变量 y 那么它将被覆盖.

The solution other users are suggesting is not equivalent as it does not apply the var to y. If there is a global variable y then it will be overwritten.

// Overwrites global y
var x = y = 'foo';

正确地将 var 应用到局部变量是一个很好的做法,为了简洁起见不要省略它.

It is a good practice to correctly apply var to local variables and not omit it for the sake of brevity.

这篇关于var x, y = 'foo';这能实现吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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