2
window.onload = function() {
  var arr = new Array;
  var jsonObj = {
    "123": "234"
  };
  arr['v'] = "234";
  arr[0] = jsonObj;
  arr[1] = jsonObj;
  console.log(JSON.stringify(arr));
}

The above code result is :

[{"123":"234"},{"123":"234"}]

I don't know why the arr['v'] disappeared?

2

4 Answers 4

4

Object and Array are not parsed to JSON the same way.

an Array will only include the numeric keys, and an Object will include all of its keys:

var Arr = [], Obj ={};

Arr[0] = Obj[0] = 'a';
Arr[1] = Obj[2] = 'b';
Arr['key'] = Obj['key'] = 'c';

console.log(JSON.stringify(Arr));
console.log(JSON.stringify(Obj));

so in your case, you could simply use an Onject instead of an array:

var arr = new Object;
var jsonObj = {"123":"234"};
arr['v'] = "234";
arr[0] = jsonObj;
arr[1] = jsonObj;
console.log(JSON.stringify(arr));

Sign up to request clarification or add additional context in comments.

Comments

0

Actually, JSON.stringify will ignore non-numeric keys in Array during the Array JSON serialization. From the latest ECMA Spec, in section "24.3.2.4 Runtime Semantics: SerializeJSONArray ( value )", we know JSON.stringify only utilizes length of Array and related numeric keys to do the serialization, and Array length will not be affected by its non-numeric keys. So it is now clear why 'v' (non-numeric keys) disappear in your final result.

Comments

0

You can't use a string as an array index, unless it is a string representation of an integer.

Therefore, arr['v'] has no meaning.

This stackoverflow question goes into more detail, but the relevant part:

Yes, technically array-indexes are strings, but as Flanagan elegantly put it in his 'Definitive guide':

"It is helpful to clearly distinguish an array index from an object property name. All indexes are property names, but only property names that are integers between 0 and 232-1 are indexes."

Comments

-1

In JavaScript, basically two types of array, Standard array and associative array. Standard array is defined by [], so 0 based type indexes. And in associative array is defined by {}, in this case you can define string as keys. So in your code you are using both is single array, that's not acceptable. So define the another array if you want strings keys.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.