有有很多方法o也創建數組。
例如
// creates the same array but with a lot less typing.
var personnel = [ // I have added a new line and then indented the nested arrays
["Name0","Age0","Address0"], // adds an array in side the first
["Name1","Age1","Address1"], // you separate all the items in the array with commas
]; //close the array.
有些人喜歡把它攤開更進一步像
var personnel = [ // always put the first opening braket here
[
"Name0", // again indenting so it is easy to see where you are at
"Age0",
"Address0", // Javascript used not let you have a comma on the last
// element. Some people still think that should be enforced
// and some IDE will report it as an error. It is up to you.
],[ // close the first and open the second array
"Name1",
"Age1",
"Address1"
],
]; //close the array.
然後非常緊湊所有在一行。
var personnel = [["Name0","Age0","Address0"],["Name1","Age1","Address1"]];
您可以將陣列到陣列
var person0 = ["Name0","Age0","Address0"];
var person1 = ["Name1","Age1","Address1"];
var personnel = [person0, person1]; //the two arrays inserted into another array;
或
var personnel = []; // create an empty array;
personnel[0] = person0; // puts person0 array as the first item
personnel[1] = person1; // and the second array as the second item
而我個人最喜歡使用String.split
方法分割字符串,並創建一個數組。
"Name0,Age0,Address0".split(","); // splits the string were there are ',' commas
// creates the array ["Name0","Age0","Address0"];
分隔符可以是任何東西
"Name0 Age0 Address0".split(" "); //in this case a space is used
甚至可以分割上的話
"Name0 banana Age0 banana Address0".split(" banana "); // splits at space banana space
所以容易產生採用分體式嵌套數組。如果你有很長的列表,你想把它放入數組,那麼很方便。
var personnel = [
"Name0,Age0,Address0".split(","),
"Name1,Age1,Address1".split(","),
];
所有這些技術創造了完全相同的陣列,並且還有更多的方式來做到這一點。沒有正確或錯誤的方式,所以選擇適合你和愉快的編碼。
提高你的風格不僅使得它更容易和更快地編寫代碼,但也使人們更方便找到的錯誤和缺陷。
BTW script標籤不需要type="text/javascript"
你需要的是<script>
和關閉標籤的代碼之後</script>
類型默認爲文本/ JavaScript的
也可參考[括號陣列(之差)和(HTTP ://stackoverflow.com/a/1273936/4677505),你應該使用寫這個:'personnel [1] = []'。 或者您可以編寫: 'personnel [1] = [ 「Name1」,「Age1」,「Address1」 ]' – Ziki