简体   繁体   中英

javascript assoc array add key value pairs unexpected result

This is probably head-buttingly obvious, but why am I not getting the expected JSON string when adding a key-value pair to this javascript array?

Next step: As code reveals, I actually wish to have two data sets in the object.

jsFiddle here - Weird, at moment only "works" in Chrome

var myKey = "123", myVal="Car";
var arrSummat = new Array();

$('#mybutt').click(function(){
    arrSummat["987"] = "Boat";
    //arrSummat[myKey] = myVal;
    var test = JSON.stringify(arrSummat);
    alert(test);
});

In JavaScript building an associate array* or hash map or object may not be terribly obvious. For one, everything is ultimately an object and so the syntax used with associative arrays is valid on everything that isn't an "associate array" which is probably where the confusion arises. First let's address the issue at hand. You're probably wanted to use an object instead of an array:

arrSummat = {};
arrSummat["987"] = "Boat";
console.log(JSON.stringify(arrSummat)); // => {"987":"Boat"}

When running your fiddle (in Chrome) I pretty much get an array with 986 null values and then "Boat" (I may be wrong, I'm not hand counting the null s in that alert).

Now that you're original question is resolved I'd like to point out two things you may want to start doing differently:

Prefer shorthand syntax for objets and arrays. The two examples are functionally the same but you should prefer the second for most purposes.

var myArr = new Array();
var myObj = new Object();

Is the same as:

var myArr = [];
var myObj = {};

The shorthand can even come with some basic values:

var myArr = [1, 2, 3];
var myObj = {one: "1", two: "2"};

Secondly, never use an Array object as anything other than an array. It is syntactically valid to do so but it will produce unexpected results (as you have seen here).

  • There is no "associative array" in JavaScript, but Objects are commonly used as a substitute and provide similar functionality.

Revised jsFiddle Link

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