首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

JavaScript alert 物件顯示 "[object Object]" 含義解析

     編輯:程式設計綜合問答

alert(obj) 顯示 [object Object] 是因為:

  • 第一個 `object`:Object.prototype.toString 回傳格式 [object [[Class]]] 中的固定前綴,表示「這是一個物件」。
  • 第二個 `Object`:內部 `[[Class]]` 屬性值,對應建構函數名稱(此處為 `Object`)。

驗證範例

function Obj() {}
var obj = new Obj();
alert(obj);                    // [object Object]
alert(Object.prototype.toString.call(obj)); // [object Object]

var arr = [1,2,3];
alert(arr);                    // 1,2,3 (Array 覆寫 toString)
alert(Object.prototype.toString.call(arr)); // [object Array]

var dt = new Date();
alert(Object.prototype.toString.call(dt));  // [object Date]

實用技巧:精確判斷型別

function typeOf(obj) {
  return Object.prototype.toString.call(obj).slice(8, -1); // "Object", "Array", "Date", "RegExp"...
}
console.log(typeOf({}));      // "Object"
console.log(typeOf([]));      // "Array"
console.log(typeOf(null));    // "Null"
console.log(typeOf(undefined)); // "Undefined"

調試建議

  • 開發時勿用 `alert(obj)`,改用 `console.log(obj)`、`console.dir(obj)` 可展開屬性檢視。
  • 需字串化時用 `JSON.stringify(obj)` (注意循環引用)。
  • ES2019+ 可用 `Object.prototype.toString.call(obj)` 做精確型別檢查,比 `typeof` 更可靠。

結論:[object Object] 只是預設 `toString()` 回傳格式,第一個 `object` 是固定字面量,第二個是內部類別標籤。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved