简体   繁体   English

为什么在array.push中调用Object.create返回一个空对象列表?

[英]Why call Object.create inside an array.push returns a list of empty objects?

I need to create an array of objects which value of the properties is set dinamically based on an existent array of objects that contains server response. 我需要创建一个对象数组,其属性值基于包含服务器响应的对象数组的存在而动态设置。

The flow in this code seems correct to me (also according to some articles on the web) but all I receive as result is an array of n empty objects (neither id: null is displayed). 这段代码中的流程对我来说似乎是正确的(根据网络上的一些文章),但是我收到的所有结果都是n个空对象的数组(均未显示id:null)。

infoForecasts = [];

buildWidget() {
    this.listForecasts.map( (i) => {
        const ser = this.utilitiesService;
        return this.infoForecasts.push(
            Object.create(
                {
                    id: null,
                    time: ser.getCurrTime(ser.getDateTime(i.dt))
                }
            )
        );
    });
}

I also tried to: 我还试图:

...

time: Object.values(ser.getCurrTime(ser.getDateTime(i.dt))

but anything changed. 但一切都变了。

What am I doing wrong? 我究竟做错了什么?

The map() method creates a new array with the results of calling a provided function on every element in the calling array. map()方法创建一个新数组,并在调用数组中的每个元素上调用提供的函数。

It should not be use to loop an array, use forEach() instead. 它不应用于循环数组,而应使用forEach()

What i suggest you to do is using reduce() like this : 我建议你做的是使用reduce()这样的:

this.listForecasts.reduce(
  (acc, cur) => [
    ...acc,
    {
      id: null,
      time: this.utilitiesService.getCurrTime(
        this.utilitiesService.getDateTime(cur.dt)
      )
    }
  ],
  []
);

however if you're only trying to push something then Array.push({ id: '', time: '' }) should be perfectly fine ! 但是,如果您仅尝试推送内容,则Array.push({ id: '', time: '' })应该很好!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM