简体   繁体   中英

Weird behavior of javascript

Please see attached screenshot. See pendingApp property of Object. when I am debugging in eclipse then pendingApp show array of object, Which is correct! But when I am JSON.stringify(object) then showing me empty Array. Eclipse图片

终端图片

Please let me know reason of this behavior. I think I am not aware with any Java-Script thought/concept ?? :P :)

When I will save this Object into DB then blank array of pendingApp will be stored !!

var pending_app = [];
var new_record = {"pendingApp" : [], "installedApp" :[] };
....SOME CODE+conditions HERE....
 pending_app[appId] = {'action' : action };
 new_record.pendingApp = pending_app;
// create app-config data
 return app_model.create(new_record); //will return promise object

It's not a weird behaviour but a common mistake of using an Array to store key-value data.

Short Answer : Use a literal Object to store these data


While you can add properties on every objects in Javascript, you cannot iterate over them with the default array mechanisms

for (var i = 0; i < array.length; i++){}
array.forEach();

Simple demonstration :

var array = [];
array["anId"] = 1;
array.length; // 0

array[4294967295] = 1; // Indice >= unsigned 32-bit Max Value
array.length; // 0
array[4294967295]; // 1

So JSON.stringify with the ECMAScript 5 Specification will use the Array mechanism to iterate over all items and will find nothing.

Unlike Objects that you can list properties with

Object.keys(array); // ["anId"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM