2016-01-15 220 views
0

我試圖創建一個多維和關聯數組。我試過類似PHP的語法,但它不起作用。怎麼解決?多維和關聯數組的正確語法

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"; 
+1

你可以使用一個對象? – Script47

+1

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Creating_new_objects – Quentin

回答

1

使用對象:

var var_s = {"books":{}, "films": {}}; 
var_s["books"]["book1"] = "good"; 
-> {books: {book1: "good"}, films: {}} 
0

你想反對文字語法:

var_s = { 
    books: { 
     book1: "good", 
     book2: "bad" 
    }, 
    films: { 
     film1: "good", 
     film2: "bad" 
    } 
} 

檢索值:

var myBook = var_s.books.book1 

設置:

var_s.books.book3 = "terrible" 

我建議您閱讀You Don't Know JS以獲得JS基礎知識的良好速成課程。 Chapter 2 of Book 1具體涵蓋的對象和初始化,

0

你可以使用對象,

var Book = { 
    'bookOne': 'good', 
    'bookTwo': 'bad' 
}; 

/** Output => good **/ 
console.log(Book.bookOne); 

注:如果需要,你可以把一個數組對象之內。

閱讀材料

Working with Objects