TypeError: undefined 在 JavaScript 中不可迭代
TypeError: undefined is not iterable in JavaScript
undefined is not iterable 错误发生在我们尝试使用undefined
右侧值的数组解构时,例如
const [name] = undefined
.
要解决该错误,请确保仅对有效数组使用数组解构。
索引.js
// ⛔️ TypeError: undefined is not iterable const [a, b] = undefined;
要解决该错误,您可以提供一个空数组的回退值。
索引.js
const [a, b] = undefined || []; console.log(a); // 👉️ a console.log(b); // 👉️ b
我们使用
逻辑 OR (||)
运算符,如果左边的值是假的(例如 ),它返回右边的值undefined
。
JavaScript 中的假值是:null
, undefined
, 0
, false
, ""
(空字符串),NaN
(不是数字)。
如果上述六个值中的任何一个位于逻辑或 (||) 运算符的左侧,我们将返回一个空数组。
如果您无法找到错误发生的确切位置,请查看浏览器控制台或终端(如果使用 Node.js)中的错误消息。
上面的截图显示错误发生在index.js
line 上的文件中4
。
如果您调用需要数组但不提供参数的函数,也可能会发生该错误。
索引.js
function hello(arr) { const [a, b] = arr; } // ⛔️ undefined is not iterable hello();
尝试从undefined
值中解构会引发错误。在这种情况下,您可以使用逻辑或 (||) 运算符传递回退值或为函数参数设置默认值。
此代码示例显示了如何执行这两项操作。
索引.js
function hello(arr = []) { const [a, b] = arr || []; } hello();
如果在调用函数时没有提供任何值或undefined
传递了一个值,则该arr
变量将设置为一个空数组。
结论
undefined is not iterable 错误发生在我们尝试使用undefined
右侧值的数组解构时,例如
const [name] = undefined
.
要解决该错误,请确保仅对有效数组使用数组解构。