简体   繁体   English

为什么我将同一个对象放入数组?

[英]Why am I getting the same object pushed into my array?

I'm trying to build an array of places from Yelp's response. 我正在尝试根据Yelp的回应建立一系列场所。 However, after pushing and passing my array into the callback to be returned I end up with the same 4 places instead of 4 unique places. 但是,在将我的数组传递并传递到回调中以返回后,我得到的是相同的4个地方,而不是4个唯一的地方。

    let rawResult = arrayBusinesses.jsonBody.businesses;
    let arrVenues = new Array();
    // console.log(rawResult);
    let venue = {
        type: 'venue',
        id: '',
        latitude: null,
        longitude: null,
        title: '',
        address: ''
       // thumb_url: ''
    };


    for (let i = 0; i < 5; i++) {
        console.log('i', i);
        (function(j){
            console.log('j' + j);
            let bus = rawResult[j];
            venue.type = 'venue';
            venue.id = j+'a';
            venue.latitude = bus.coordinates.latitude;
            venue.longitude = bus.coordinates.longitude;
            venue.title = bus.name;
            venue.address = bus.location.address1;
            arrVenues.push(venue);
        })(i);
    }

your code is hard to read how about something like 您的代码很难看懂

const arrVenues = rawData.slice(0, 5)
.map((place, index) => (
  {
    type: 'venue',
    id: `${index}a`,
    latitude: place.coordinates.latitude,
    longitude: place.coordinates.longitude,
    title: place.name',
    address: place.location.address,
 }
));

How ever to answer your question the problem is that you keep pushing the same object every time. 如何回答您的问题,问题是您每次都不断推动相同的对象。 when you do arrVenues.push(venue) is always the same object, literally the same memory location. 当您执行arrVenues.push(venue) ,始终是同一对象,实际上是相同的内存位置。 since you never take time to make a copy of the object and just modify is properties you end up with an array of the same object. 由于您从不花时间来复制对象,而只需修改属性,您最终会得到同一对象的数组。

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

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