-4

I wasn't sure what to call it for the title,

How can I create an array like this in JavaScript?

var per_kg_list = new Array(
    '03749' => '3.000',
    '03750' => '4.000',
    '03751' => '5.000',
);
3

4 Answers 4

3

You can have an array of objects containing key-value pairs, like this:

var per_kg_list = [
    {'03749': '3.000'},
    {'03750': '4.000'},
    {'03751': '5.000'}
];

Alternatively, you can have an object containing key-value pairs, like this:

var per_kg_list = {
    '03749': '3.000',
    '03750': '4.000',
    '03751': '5.000'
};
Sign up to request clarification or add additional context in comments.

2 Comments

What was the purpose of editing my answer to add one whitespace character?
So I could remove my downvote since you updated your answer :)
0

In JavaScript, array doesn't allow to use string as indexes. You may consider to use dictionary:

var per_kg_list = {};
per_kg_list['03749'] = '3.000';
per_kg_list['03750'] = '4.000';
per_kg_list['03751'] = '5.000';

3 Comments

It's just called an object in JS
@JuanMendes Yeah. True.
Also, Array extends Object, so it can be used as map, but you shouldn't. It's really using strings and the keys that parse to integers are taken into account when calculating the length property, more or less Try a=[0]; a["0"] = 1;
0

Someone answered the best way to initializing a JavaScript array with values:

var per_kg_list = {'03749': '3.000', '03750': '4.000', '03751': '5.000'};

Comments

0

You can use associative array notations. They are just JavaScript objects with properties:

var set = new Object();
set['Document language'] = 'HTML5';
set['Styling language'] = 'CSS3';
set['JavaScript library'] = 'jQuery';
set['Other'] = 'Usability and accessibility';

6 Comments

They are not equivalent
@JuanMendes Okay .. I am just learning JavaScript and this is my first JavaScript answer .. can u pls let me know where is the issue ?
Array extends Object with methods like push, pop, and you would give it numeric indices. If you don't need that behavior, you should just use object.phabricator.com/docs/phabricator/article/…
The comment about the longhand for maps is wrong in the article you linked to, not sure if it's a typo
Here's a link from Google's style guide, explaining why you shouldn't use arrays as associative maps google-styleguide.googlecode.com/svn/trunk/…
|

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.