我希望能够将值推送到下面的关联数组中。
var car = [];
car [0] = {type: "audi", age: "10"};
car [1] = {type: "bmw", age: "6"};
car [2] = {type: "tesla", age: "2"};
我尝试使用推送的方法如下。使用 car.length 将其推入我们的汽车阵列的下一行,因为它总是高一个。我不知道这是不是很好的做法,但我想它确实有效。
value1 = "hyundai"
value2 = "14";
car[car.length].push({type: value1, age: value2});
我绝对不能让这个工作,而在这一点上,作为一个初学者JS&#,呃,我没有想法。
答案 0 :(得分:1)
您的代码的问题在于您没有调用推送有效对象。请尝试以下代码:
<script>
var car = [];
car [0] = {type: "audi", age: "10"};
car [1] = {type: "bmw", age: "6"};
car [2] = {type: "tesla", age: "2"};
console.log(car);
value1 = "hyundai"
value2 = "14";
car.push({type: value1, age: value2});
console.log(car);
</script>
答案 1 :(得分:1)
你可以car.push({type: value1, age: value2});