Array.push方法生成相同的内部JSON值

时间:2017-11-29 16:13:58

标签: javascript jquery arrays

我正在生成一个带有一些值的var stamp = {}并将{em> PUSH 两个不同的变量 OBJ1 OBJ2 添加到{{1以下是我的代码。

var stampsOnCanvas = new Array();

function addStamp2Array(stampName,pageNo,x,y,isAdded,src,height,width,         stampParameters,stampImgName){

var stampsOnCanvas = new Array();

}

现在,我正在尝试推送两个var stamp = {}; var mObj = new Object(); stamp = new Stamp(stampName, pageNo, x, y, scale, isAdded, src, height, width, stampParameters, stampScale, stampImgName); mObj=JSON.parse(JSON.stringify(stamp)); //Copy your stamp obj to new Object if (stampsOnCanvas == null || stampsOnCanvas == undefined || stampsOnCanvas.length == 0) { stampsOnCanvas[0] = mObj; } else { if (stampsOnCanvas.indexOf(mObj) == -1) { if (stampsOnCanvas.length <= 1) { // add new stamp in the array stampsOnCanvas.push(mObj); } else { // add repeated stamp in the array(can append "_x" if repeated the // same id ) count++; mObj.stampName = mObj.stampName + '_' + count; stampsOnCanvas.push(mObj); } } mObj = new Object(); 变量 OBJ1 OBJ2 ,它们分别具有以下值。

stamp

{
    "pageNo": 1,
    "xCord": 447,
    "yCord": 139,
    "height": 24.444444444444443,
    "width": 24.444444444444443,
    "parameters": [{
            "stampName": "TEXT",
            "paramSeqNo": 1,
            "paramName": "TEXT",
            "paramType": "Application",
            "paramValue": "1111111111111111"
        }
    ]
}

但是,当我表演时

{
    "pageNo": 1,
    "xCord": 74,
    "yCord": 310,
    "height": 24.444444444444443,
    "width": 24.444444444444443,
    "parameters": [{
            "stampName": "TEXT",
            "paramSeqNo": 1,
            "paramName": "TEXT",
            "paramType": "Application",
            "paramValue": "222222222222222222"
        }
    ]
}

推送后,我在数组中的两个变量中得到for(var c=0;c<stampsOnCanvas.length;c++) { console.log("stamps after == "+c+" "+JSON.stringify(stampsOnCanvas[c])); } 。我尝试过深拷贝和浅拷贝方法,而不是 PUSH 。但在"paramValue": "222222222222222222"推动 OBJ1 OBJ2 时,我不知道我在哪里错过了逻辑。 问题是 OBJ1 stampsOnCanvas应该是1111111111111111,而 OBJ2 "paramValue"应该是222222222222222222在控制台日志中。但相反,我在控制台日志中的两个对象中获得"paramValue"值为222222222222222222。可能是什么问题?

1 个答案:

答案 0 :(得分:0)

也许这会有所帮助,当我拿出对象存在并运行时,似乎你正在使用对象:

let stampsOnCanvas = new Array();

function addStamp2Array(stampParameters, stampImgName) {
  let stamp = {};

  //Create a stamp with given values
  stamp = stampParameters + stampImgName;
  console.log(stamp);
  if (stampsOnCanvas.length == 0) {
    //If it is first stamp, than set to first
    stampsOnCanvas[0] = stamp;
    console.log(stampsOnCanvas);

  } else {
    //If it is second of more...
      stampsOnCanvas.push(stamp);
      console.log(stampsOnCanvas);

  }
}


console.log('firing');

addStamp2Array(1111111, "TEXT");
addStamp2Array(2222222, "TEXT");

我得到2个单独的值,但你有一个对象通过push

写这些

结帐这个SO答案了解更多信息:

调用push不会复制您的对象,因为JavaScript对象是通过引用传递的:您将每个数组条目推送相同的Object。

https://stackoverflow.com/a/19055093/6627119