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

时间:2016-02-25 06:38:48

标签: javascript arrays

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

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 = [],因为我需要键才能使用我的应用程序的反应性才能使用默认值。

1 个答案:

答案 0 :(得分:1)

检查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);