【问题标题】:My javascript array keeps getting overwritten when trying to add a new object尝试添加新对象时,我的 javascript 数组不断被覆盖
【发布时间】:2019-05-24 18:33:32
【问题描述】:

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

我尝试了一个普通的 array.push({data}) 和 ES6 spread [...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 的障碍和“你好代码”的信息 当它被添加到数组中时,数组看起来像:

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

【问题讨论】:

    标签: javascript node.js nativescript


    【解决方案1】:

    我打算将此作为评论,但想通过编写一些简化版本的代码来向您展示我认为您做错了什么的示例。

    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,
    });
    
    
    
    

    【讨论】:

    • 您应该注意,这是一个浅传播; data 中包含的任何对象都将被引用,对这些对象的任何更改都将反映在两者中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-07
    • 2021-06-04
    • 1970-01-01
    • 2022-01-20
    • 2021-03-28
    • 1970-01-01
    • 2016-05-08
    相关资源
    最近更新 更多