gpt4 book ai didi

javascript - 迭代对象数组并将它们放入单独的工厂函数中的最佳方法是什么?

转载 作者:行者123 更新时间:2023-12-03 00:20:32 24 4
gpt4 key购买 nike

例如,假设我有 data = [{car: "ford", year: "1982"}, {car: "toyota", year: "1999"}] .

  //factory function
function Car(type, year) {

return {
type,
year,
identity() {

return "I am a " + year + " " + type

}

}

}

let arr = []
data.forEach((x) => {

// would this be the correct way to turn these into factory function
// objects?
arr.push(Car(x.car, x.year))

})

是否有更好的方法来做到这一点,以便每个 Car() 都有一个与之关联的变量?

最佳答案

var data = [{car: "ford", year: "1982"}, {car: "toyota", year: "1999"}];

function Car(type, year) {

return {
type,
year,
identity() {

return "I am a " + year + " " + type

}

}

}

// Use Map. Map iterates over your array, at each
// element it will call the supplied callback argument
// with the current element. Whatever your function returns
// will be mapped to a new array
// at the same index as the element passed to your callback

const arr = data.map(({ car, year }) => Car(car, year))

console.log(arr);

关于javascript - 迭代对象数组并将它们放入单独的工厂函数中的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54332186/

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