This question already has an answer here:
这个问题在这里已有答案:
- How to append something to an array? 31 answers
如何将某些内容附加到数组中? 31个答案
I'd like to be able to push values into the associative array below.
我希望能够将值推送到下面的关联数组中。
var car = [];
car [0] = {type: "audi", age: "10"};
car [1] = {type: "bmw", age: "6"};
car [2] = {type: "tesla", age: "2"};
The method I've tried using to push is the following. Using car.length to push it into the next line of our car array, as it'll always be one higher. I don't know if that's good practice, but I guess it works.
我尝试使用推送的方法如下。使用car.length将其推入我们的汽车阵列的下一行,因为它总是高一个。我不知道这是不是很好的做法,但我猜它有效。
value1 = "hyundai"
value2 = "14";
car[car.length].push({type: value1, age: value2});
I absolutely cannot get this to work, and at this point, as a beginner JS'er, I'm out of ideas.
我绝对不能让这个工作,而在这一点上,作为一个初学者JS'er,我没有想法。
2 个解决方案
#1
1
The issue with your code is that you were not calling push on a valid object. Please try this code:
您的代码的问题是您没有调用推送有效对象。请尝试以下代码:
<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>
#2
1
you can just car.push({type: value1, age: value2});
你可以只是car.push({type:value1,age:value2});
#1
1
The issue with your code is that you were not calling push on a valid object. Please try this code:
您的代码的问题是您没有调用推送有效对象。请尝试以下代码:
<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>
#2
1
you can just car.push({type: value1, age: value2});
你可以只是car.push({type:value1,age:value2});