我需要这样的东西:
var fruits[1] = ["Banana", "Orange", "Apple", "Mango"];
fruits[2] = ["Banana"];
fruits[1].push("Lemon");
fruits[2].push("Orange");
但这不适用于javascript。
有没有办法在javascript中实现这种机制?
答案 0 :(得分:6)
首先,将fruits
本身初始化为数组
var fruits = [];
fruits[1] = ["Banana", "Orange", "Apple", "Mango"];
fruits[2] = ["Banana"];
fruits[1].push("Lemon");
fruits[2].push("Orange");
console.log(fruits);
答案 1 :(得分:1)
您可以执行以下操作:
var fruits = []; //declared a blank array
fruits.push("Banana"); //adding 1st item
fruits.push("Orange"); //adding 2nd item
fruits.push("Apple"); //adding 3rd item
fruits.push("Mango"); //adding 4th item
//if you want to update any item then simply do the following
fruits[2] = "Lemon"