SyntaxError: missing variable name
JavaScript 異常“缺少變數名”是一個常見錯誤。它通常是由於省略了變數名或拼寫錯誤造成的。
訊息
SyntaxError: missing variable name (Firefox) SyntaxError: Unexpected token '='. Expected a parameter pattern or a ')' in parameter list. (Safari)
錯誤型別
SyntaxError
哪裡出錯了?
變數缺少名稱。原因很可能是打字錯誤或忘記了變數名。請確保在 = 符號之前提供了變數的名稱。
同時宣告多個變數時,請確保前幾行/宣告沒有以逗號而不是分號結尾。
示例
缺少變數名
js
const = "foo";
很容易忘記為變數賦值一個名稱!
js
const description = "foo";
保留關鍵字不能作為變數名
有一些變數名是保留關鍵字。您不能使用這些關鍵字。抱歉 :(
js
const debugger = "whoop";
// SyntaxError: missing variable name
宣告多個變數
宣告多個變數時要特別注意逗號。是否存在多餘的逗號,或者您使用了逗號而不是分號?您是否記得為所有 const 變數賦值?
js
let x, y = "foo",
const z, = "foo"
const first = document.getElementById("one"),
const second = document.getElementById("two"),
// SyntaxError: missing variable name
已修復版本
js
let x,
y = "foo";
const z = "foo";
const first = document.getElementById("one");
const second = document.getElementById("two");
陣列
JavaScript 中的 Array 字面量需要用方括號括起來。這行不通
js
const arr = 1,2,3,4,5;
// SyntaxError: missing variable name
這將是正確的
js
const arr = [1, 2, 3, 4, 5];