I'm trying to create an multidimensional and associative array. I'm tried a PHP-like syntax but it doesn't work. How to solve?
var var_s = ["books", "films"];
var_s["books"]["book1"] = "good";
var_s["books"]["book2"] = "bad";
var_s["films"]["films1"] = "bad";
var_s["films"]["films2"] = "bad";
-
1You could use an object?Script47– Script472016年01月15日 11:19:05 +00:00Commented Jan 15, 2016 at 11:19
-
1developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/…Quentin– Quentin2016年01月15日 11:21:39 +00:00Commented Jan 15, 2016 at 11:21
3 Answers 3
Use objects:
var var_s = {"books":{}, "films": {}};
var_s["books"]["book1"] = "good";
-> {books: {book1: "good"}, films: {}}
answered Jan 15, 2016 at 11:22
Martin Schneider
3,2784 gold badges21 silver badges30 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
You want object literal syntax:
var_s = {
books: {
book1: "good",
book2: "bad"
},
films: {
film1: "good",
film2: "bad"
}
}
Retrieving a value:
var myBook = var_s.books.book1
Setting:
var_s.books.book3 = "terrible"
I recommend reading You Don't Know JS for a good crash course in JS basics. Chapter 2 of Book 1 specifically covers objects and initialization,
answered Jan 15, 2016 at 11:22
N3dst4
6,4552 gold badges23 silver badges36 bronze badges
Comments
You could use objects,
var Book = {
'bookOne': 'good',
'bookTwo': 'bad'
};
/** Output => good **/
console.log(Book.bookOne);
Note: If you need, you can put an array within the object.
Reading Material
answered Jan 15, 2016 at 11:23
Script47
14.6k4 gold badges49 silver badges69 bronze badges
Comments
Explore related questions
See similar questions with these tags.
lang-js