2014-09-30 44 views
0

我有點卡住試圖做一個3維數組。 下面的代碼:對文字[顏色] [字體JavaScript 3維字符串數組

var text = new Array("purple", "red", "white"); 
text["purple", "red", "white"] = new Array("one", "two", "three"); 
text["purple", "red", "white"]["one", "two", "three"] = new Array(3); 

var color = "white"; 
var font = "one"; 
var num = "two"; 

text[color][font][num]     = new Image(); 
text[color][font][num]     = "destination"; 

它不運行,當我檢查元素,它給了我一個「的未定義無法設置屬性‘白’遺漏的類型錯誤」 ] [num] = new Image();一行。

請幫幫忙,我究竟做錯了什麼? :(

+0

'文本[「紫色」,「紅」,「白」]'是不正確的,等同於'文本[「白」] ' – techfoobar 2014-09-30 05:48:40

回答

0

你必須使用objects,不arrays

var text = { 
    purple: { 
     one: new Array(3), 
     two: new Array(3), 
     three: new Array(3) 
    }, 
    white: { 
     //... 
    }, 
    //... 
} 

然後你就可以訪問它想:

text['purple']['one'][0] 

或者

text.purple.one[0] 

而且,在我看來,以下結構可能對您有用:

var text = { 
    purple: { 
     one: { 
      image: new Image(), 
      destination: "my destination" 
     }, 
     // ... 
    }, 
    // ... 
} 

用法:

alert(text.purple.one.destination) //Will alert "my destination" 
0
text["purple", "red", "white"] 

這是無效的。

設置

var text = new Array("purple", "red", "white"); 

文本,數組後,可以訪問使用你感興趣的項目的從零開始的索引傳遞。

text[0] // will be purple 
text[1] // will be red 
text[2] // will be white 

數組,你可以看到可以使用他們的索引訪問,而不是他們持有的價值。如果你想通過值訪問的集合,使用普通的對象,而不是

var text = { 
    "purple": { 
    "one": { 
     "one": null, 
     "two": null, 
     "three": null 
    }, 
    "two": { 
     "one": null, 
     "two": null, 
     "three": null 
    }, 
    "three": { 
     "one": null, 
     "two": null, 
     "three": null 
    } 
    }, 
    "red": { 
    "one": { 
     "one": null, 
     "two": null, 
     "three": null 
    }, 
    "two": { 
     "one": null, 
     "two": null, 
     "three": null 
    }, 
    "three": { 
     "one": null, 
     "two": null, 
     "three": null 
    } 
    }, 
    "white": { 
    "one": { 
     "one": null, 
     "two": null, 
     "three": null 
    }, 
    "two": { 
     "one": null, 
     "two": null, 
     "three": null 
    }, 
    "three": { 
     "one": null, 
     "two": null, 
     "three": null 
    } 
    } 
} 

var color = "white"; 
var font = "one"; 
var num = "two"; 

text[color][font][num]     = new Image(); 
text[color][font][num]     = "destination"; // you are overwriting here