JavaScript 是弱型別語言,但仍有型別系統。要判斷變數型別,最常見的是使用 typeof 運算子。不過 typeof 有些結果容易讓人誤解。
const myFunction = function () {};
const myObject = { foo: 'bar' };
const myArray = ['a', 'b', 'c'];
const myString = 'hello';
const myNumber = 3;
console.log(typeof myFunction); // function
console.log(typeof myObject); // object
console.log(typeof myArray); // object
console.log(typeof myString); // string
console.log(typeof myNumber); // number
console.log(typeof null); // object
可以看到,陣列與 null 都會回傳 object,這是 typeof 的限制。
若要準確判斷陣列,可以使用 Object.prototype.toString.call():
if (Object.prototype.toString.call(myArray) === '[object Array]') {
console.log('這是陣列');
}
這種方式比單純依賴 typeof 更可靠。理解型別判斷的限制,有助於避免條件式寫錯。