简体   繁体   English

es6在IF内部声明一个变量(如es5)

[英]es6 declare a variable inside an IF ( like es5 )

OK, this has reached a point where I am annoyed and was not able to solve this. 好的,这已经使我感到恼火,无法解决此问题。

In ES5 I would frequently do something like... 在ES5中,我经常会做类似...

if( (users = resp.results) && users.length > 0 ) {
    // do something with users
}

For a moment, let's forget about the scoping and the implication and all of that... 一会儿,让我们忘记范围界定和含义以及所有这些……

Babel does not like this syntax anymore starting ES6 nor does the Chrome console. Babel不再从ES6开始喜欢这种语法,Chrome控制台也不再喜欢。

Is there an equivalent syntax now in ES6? ES6中现在有等效的语法吗?

If you want it to be valid when using 'use strict' , which Babel enforces, you need to declare users first. 如果希望在使用Babel强制使用的'use strict'时有效,则需要首先声明users If you are not using Babel or 'use strict' your original code will work just fine. 如果您不使用Babel或“严格使用”,则原始代码将可以正常工作。

var users;
if( (users = resp.results) && users.length > 0 ) {
    // do something with users
}

will work with 'use strict' . 将与'use strict'使用'use strict'

You could also manually remove 'use strict' from the top of your converted babel code if you want to continue using this trick. 如果您想继续使用此技巧,也可以从转换后的babel代码的顶部手动删除'use strict'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM