英文:
Array destructuring assignment to default parameters: keeping both array and items variables
问题
我试图一次性兼顾两全其美:使用个别变量来引用特定函数调用的结果,以及使用包含所有这些结果的数组变量。
如果您将下面的代码粘贴到您的浏览器控制台或节点运行时中,它将“只是工作™”没有错误:
function useFieldX() { return { state: 'x' } }
const fields = [ fieldX = useFieldX()]
console.log(fields) // [{ state: 'x' }]
console.log(fieldX) // { state: 'x' }
console.log(fieldX === fields[0]) // true
但是bundling/transpiling this code会抛出ReferenceError: fieldX is not defined
。可能的原因是什么?
注意:我理解fieldX
变量理论上应该在当前范围内已经声明才能被赋值,但为什么它在上述上下文中却能正常工作呢?
英文:
I'm trying to get the best of both worlds in one go: individual variables to reference a specific function call result, and an array variable with all those results.
If you paste the code below in your browser console or node runtime it will _just work™ without errors:
function useFieldX() { return { state: 'x' } }
const fields = [ fieldX = useFieldX()]
console.log(fields) // [{ state: 'x' }]
console.log(fieldX) // { state: 'x' }
console.log(fieldX === fields[0]) // true
But bundling/transpiling this code throws ReferenceError: fieldX is not defined
. What might be the reason for that?
Note: I understand that fieldX
variable should in theory be already declared in the current scope to be assigned, but why does it work in the abovementioned contexts though?
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
function useFieldX() { return { state: 'x' } }
const fields = [ fieldX = useFieldX()]
console.log(fields) // [{ state: 'x' }]
console.log(fieldX) // { state: 'x' }
console.log(fieldX === fields[0]) // true
<!-- end snippet -->
答案1
得分: 3
在[严格模式](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode)下禁止对隐式全局变量进行赋值,这会将几种可能导致错误的不良实践转变为错误。仅在浏览器或节点repl中运行的代码不运行在严格模式。
<!-- 开始片段: js 隐藏: false 控制台: true babel: false -->
<!-- 语言: lang-js -->
!function () {
implicitGlobal1 = 1;
}();
!function () {
"use strict";
implicitGlobal2 = 1;
}();
<!-- 结束片段 -->
由Parcel生成的代码(你应该在问题中提及,并不依赖于别人跟随链接访问不同网站上的项目并在package.json中查找)在严格模式下运行。
英文:
Assignment to implicit globals is forbidden in strict mode which turns several bad practises likely to lead to mistakes into errors. Code just running in a browser or a node repl doesn't run in strict mode.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
!function () {
implicitGlobal1 = 1;
}();
!function () {
"use strict";
implicitGlobal2 = 1;
}();
<!-- end snippet -->
Code generated by Parcel (which you should mention in your question and not depend on people to follow a link to your project on a different site and dig around in your package.json to identify) runs in strict mode.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论