在 for...of 中没有变量声明在 .js 中有效但在 .mjs 中无效
without variable declaration in for...of is working in .js but not in .mjs
index.js
let rows = [{ location: 10 }, { location: 11 }, { location: 12 }];
for (row of rows) {
console.log(row);
}
运行 节点
$ node index.js
{ location: 10 }
{ location: 11 }
{ location: 12 }
但是为什么
index.mjs
let rows = [{ location: 10 }, { location: 11 }, { location: 12 }];
for (row of rows) {
console.log(row);
}
运行 节点
$ node index.mjs
file:///C:/Users/WF-SYS-19/Desktop/D/walkover/index.mjs:4
for (row of rows) {
^
ReferenceError: row is not defined
at file:///C:/Users/WF-SYS-19/Desktop/D/walkover/index.mjs:4:6
←[90m at ModuleJob.run (internal/modules/esm/module_job.js:152:23)←[39m
←[90m at async Loader.import (internal/modules/esm/loader.js:177:24)←[39m
←[90m at async Object.loadESM (internal/process/esm_loader.js:68:5)←[39m
.js
和 .mjs
都工作正常,
如果 row 变量声明为 const
、let
或 var
.for...of
mjs默认使用严格模式,所以不允许隐式定义。在循环中声明它 for (let row of rows) {
以绕过它。
index.js
let rows = [{ location: 10 }, { location: 11 }, { location: 12 }];
for (row of rows) {
console.log(row);
}
运行 节点
$ node index.js
{ location: 10 }
{ location: 11 }
{ location: 12 }
但是为什么
index.mjs
let rows = [{ location: 10 }, { location: 11 }, { location: 12 }];
for (row of rows) {
console.log(row);
}
运行 节点
$ node index.mjs
file:///C:/Users/WF-SYS-19/Desktop/D/walkover/index.mjs:4
for (row of rows) {
^
ReferenceError: row is not defined
at file:///C:/Users/WF-SYS-19/Desktop/D/walkover/index.mjs:4:6
←[90m at ModuleJob.run (internal/modules/esm/module_job.js:152:23)←[39m
←[90m at async Loader.import (internal/modules/esm/loader.js:177:24)←[39m
←[90m at async Object.loadESM (internal/process/esm_loader.js:68:5)←[39m
.js
和 .mjs
都工作正常,
如果 row 变量声明为 const
、let
或 var
.for...of
mjs默认使用严格模式,所以不允许隐式定义。在循环中声明它 for (let row of rows) {
以绕过它。