gpt4 book ai didi

javascript - 如何设置具有未知数量对象的数组的默认值?

转载 作者:行者123 更新时间:2023-12-03 07:35:49 25 4
gpt4 key购买 nike

我知道如何设置对象的默认值:

store.currentUser = {
username: ''
}

并为其设置新值:

store.getCurrentUser = () => {
const currentUser = Parse.User.current()
store.currentUser.username = currentUser.username
}
}

但如果我有一个数组,我就不能这样做:

store.buildings = [
// how to set the defaults here?
]

因为数组可以包含的对象数量未知:

store.findBuildings = () => {
const query = new Parse.Query(Building)
return query.find({
success: (buildings) => {
// _.map(buildings, (building) => building.toJSON())
// -> [ {name: 'Name 1'}, {name: 'Name 2'}, etc... ]
// how to give the new values to store.buildings?
},
error: (buildings, error) => {
console.log('Error:', error.message)
}
})
}

有什么办法可以做到这一点吗?

注意:我不能只执行buildings = [],因为我需要按键具有默认值才能使我的应用程序的 react 性正常工作。

最佳答案

检查this answer

Array.prototype.repeat= function(what, L){
while(L) this[--L]= what;
return this;
}

var A= [].repeat(0, 24);

或者使用第二个答案

var a = Array.apply(null, Array(24)).map(function() { return /your object here/ });
// or:
var a = Array.apply(null, Array(5)).map(Boolean).map(Number);

关于javascript - 如何设置具有未知数量对象的数组的默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35620105/

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