在 JavaScript 中,我們常用 JSON.stringify()
將物件或陣列轉為 JSON 字串。但有時你明明覺得「資料已經放進陣列」,卻發現:
JSON.stringify(now_points); // ➜ "[]"
這到底是為什麼?其實你遇到的是 「陣列被錯誤地當作物件來用」 的情況。
錯誤寫法的起點
let now_points = []; now_points["P01"] = [1, 2, 3];
你以為你對陣列加上一筆資料,但其實這是 「對陣列新增一個屬性」,而不是加到陣列的內容裡。
為什麼 JSON.stringify()
結果是空的?
因為 JSON.stringify()
只會序列化陣列中的數值項目(由索引決定的項目,例如 arr[0]
、arr[1]
),不會包含用物件語法新增的自訂屬性。
所以這樣的程式碼:
let now_points = []; now_points["P01"] = [1, 2, 3]; console.log(JSON.stringify(now_points)); // ➜ "[]"
其實建立的是一個 長度為 0 的陣列,只是這個陣列偷偷被你加了一個「非序列化的鍵」而已。
正確寫法:用 Object 而不是 Array
正確方式應該是:
let now_points = {}; // 使用物件而不是陣列 now_points["P01"] = [1, 2, 3]; now_points["P02"] = [4, 5, 6];
結果:
console.log(JSON.stringify(now_points)); // ➜ {"P01":[1,2,3],"P02":[4,5,6]}
如何判斷你犯了這個錯誤?
可以使用以下檢查方法:
console.log(typeof now_points); // 應為 "object" console.log(Array.isArray(now_points)); // 如果是 true ➜ 是陣列 console.log(Object.keys(now_points)); // 如果只有 ["P01", "P02"] ➜ 你用了物件語法加在陣列上 console.log(now_points.length); // 如果是 0 ➜ 沒有實際元素 console.log(JSON.stringify(now_points)); // 如果是 "[]" ➜ 沒有成功序列化
延伸正確範例:使用陣列包物件(如需順序)
如果你需要保持順序,也可以使用陣列包物件:
let now_points = [ { id: "P01", coords: [1, 2, 3] }, { id: "P02", coords: [4, 5, 6] } ]; console.log(JSON.stringify(now_points)); // ➜ [{"id":"P01","coords":[1,2,3]},{"id":"P02","coords":[4,5,6]}]
小結
錯誤寫法 | 結果 |
---|---|
let arr = []; arr["P01"] = [1,2,3]; |
JSON.stringify(arr) ➜ "[]" |
arr.length |
0 (實際沒元素) |
Object.keys(arr) |
["P01"] (不是索引值) |
✅ 請使用:
-
{}
建立物件資料(適合 key-value) -
[]
建立純陣列資料(適合清單/順序)
? 總結一句話:
如果你用
[]
建立資料,請確保用的是索引 (arr[0] = ...
),而不是 key (arr["key"] = ...
);否則JSON.stringify()
會給你一個空的結果,讓你以為資料不見了!
留言板
歡迎留下建議與分享!希望一起交流!感恩!