尝试添加新对象时,我的javascript数组不断被覆盖

时间:2019-05-24 18:33:33

标签: javascript node.js nativescript

我正在使用带有纯JavaScript的nativescript核心。但是我认为这不是问题所在。问题的基础是我试图将新对象添加到全局数组中,当我这样做时,以前的数据不断被新对象覆盖。

我尝试了一个普通的array.push({data})和ES6传播[... array,{data}]。这两种方法最终都用新对象覆盖了数组中的先前数据。

record-page.js

// import statements

// variables

// 'global' array of markers. 
var markers = [];

// this function opens a custom modal 
function addObsticalTapped(args) {

  // close the popup
  var page = args.object.page;
  var popup = page.getViewById("trailNotesPopup");
  isShown = false;

  popup.animate({
    translate: {
      x: 0,
      y: 500
    },
    duration: 300,
    curve: enums.AnimationCurve.easeInOut
  });

  var mainView = args.object;
  var context = {};

  geolocation
    .getCurrentLocation({
      desiredAccuracy: Accuracy.high
    })
    .then(loc => {
      curLoc = loc;
    });


  mainView.showModal(obsticalModal, context, addObsticalIcon, false);
}
exports.addObsticalTapped = addObsticalTapped;

// callback function when the modal is closed
function addObsticalIcon(didConfirm, data) {
  if (didConfirm) {
    // this is where the problem is, the markers array is being overwritten
    //     when adding another marker
    markers = [...markers, {
      type: "obstical",
      location: {
        lat: curLoc.latitude,
        lng: curLoc.longitude
      },
      data: data,
      trail_id: ""
    }];

    map.addMarkers([{
      id: markerID,
      lat: curLoc.latitude,
      lng: curLoc.longitude,
      //icon: "res://obstical_icon"
      iconPath: "./icons/obstical_icon_marker.png"
    }]);
    markerID++;

    console.log(JSON.stringify(markers));
  } else {
    console.log("closed");
  }
}

obstical-modal.js


function onShownModally(args) {
    const context = args.context;
    closeCallback = args.closeCallback;
    const page = args.object;

    vm = observableModule.fromObject(context);
    vm.set("oneSelected", oneSelected ? oneOn : oneOff);
    vm.set("threeSelected", threeSelected ? threeOn : threeOff);
    vm.set("sixSelected", sixSelected ? sixOn : sixOff);
    vm.set("nineSelected", nineSelected ? nineOn : nineOff);

    page.bindingContext = vm;
}
exports.onShownModally = onShownModally;

function onCancel(args) {
    closeCallback(false, {});
}
exports.onCancel = onCancel;

function onSubmit(args) {
    var page = args.object.page;
    var textField = page.getViewById("info");
    data.info = textField.text;
    closeCallback(true, data);
}
exports.onSubmit = onSubmit;

我希望发生的事情: 障碍物的难度为1,“ hello world”的信息为 然后将其添加到数组中,数组是正确的。 然后我添加了另一个难度为3的障碍物和“ hello code”信息 将其添加到数组后,该数组将如下所示:

[{"type":"obstical","data":{"difficulty":3,"info":"hello code"}},{"type":"obstical","data":{"difficulty":3,"info":"hello code"}}]

1 个答案:

答案 0 :(得分:2)

我本来要对此发表评论,但想向您展示一个我认为您通过编写一些简化版本的代码来做错事的例子。

const data = {
  difficulty: '1',
  info: 'hello code',
};

const markers = [];

markers.push({
  type: 'obstical',
  data: data,
});

// Here is the problem. The problem is not related to the array adding
data.difficulty = '3';

markers.push({
  type: 'obstical',
  data: data,
});

该问题与如何添加到数组无关,但与原始数据对象有关。解决方法如下:

const data = {
  difficulty: '1',
  info: 'hello code',
};

const markers = [];

markers.push({
  type: 'obstical',
  data: data,
});

// create a new object instead of mutating the existing one
const newData = {
  ...data,
  difficulty: '3',
};

markers.push({
  type: 'obstical',
  data: newData,
});