gpt4 book ai didi

javascript - 如何使用DOM元素的键和值创建对象数组?

转载 作者:行者123 更新时间:2023-12-04 09:26:43 27 4
gpt4 key购买 nike

如何创建这样的对象数组?

let cars = [
{
color: "purple",
type: "minivan",
capacity: 5
},
{
color: "red",
type: "suv",
capacity: 5
},
{
...
},
...
]

let cars = [];

$(".car").each(function() {

var color = $(this).data('color');
var type = $(this).data('type');
var capacity = $(this).data('capacity');
cars.push();
});
.car {
background: gold;
padding: 10px;
margin: 6px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="car" data-color="purple" data-type="minivan" data-capacity="5"> Car 1</div>
<div class="car" data-color="red" data-type="suv" data-capacity="5"> Car 2</div>
<div class="car" data-color="green" data-type="sedan" data-capacity="2"> Car 3</div>

最佳答案

你做得对,你需要将元素对象插入数组

let cars = [];

$(".car").each(function() {

var color = $(this).data('color');
var type = $(this).data('type');
var capacity = $(this).data('capacity');
cars.push({color, type, capacity});
});

console.log(cars)
.car {
background: gold;
padding: 10px;
margin: 6px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="car" data-color="purple" data-type="minivan" data-capacity="5"> Car 1</div>
<div class="car" data-color="red" data-type="suv" data-capacity="5"> Car 2</div>
<div class="car" data-color="green" data-type="sedan" data-capacity="2"> Car 3</div>

关于javascript - 如何使用DOM元素的键和值创建对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62978175/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com