简体   繁体   English

在JavaScript中修改原始对象

[英]Modify in original object in javascript

I have define an object in variable "c". 我在变量“ c”中定义了一个对象。 I have also make a function in which I passed a object. 我还创建了一个传递对象的函数。 When I do changes in that variable it is also changing original object but my concern is why below given statement is not working with that object. 当我在该变量中进行更改时,它也在更改原始对象,但是我担心的是为什么下面给出的语句不适用于该对象。 fiddle 小提琴

function changeParam(x, y, z) {
  x = 3;
  y = "new string";
  z["key2"] = "new";
  z["key3"] = "newer";

  z = {"new" : "object"};
}

var a = 1,
    b = "something",
    c = {"key1" : "whatever", "key2" : "original value"};
var m=c;
changeParam(a, b, c);

console.log(c)
console.log(m)

JavaScript passes object by reference. JavaScript通过引用传递对象。 To pass it by value you need to clone it before. 要通过值传递它,您需要先克隆它。

In this question you'll find options of doing it. 这个问题中,您会找到这样做的选择。 There are a lot ways of doing it, each with advantages and disadvantages. 这样做的方法很多,各有优点和缺点。 Depends on what you want from your object you can choose one. 取决于您要从对象中选择什么,可以选择一种。

Shortest way is to stringify object to JSON and parse again. 最简单的方法是将对象字符串化为JSON并再次解析。 (note that you can not save function in such object): (请注意,您无法在此类对象中保存函数):

var newObject = JSON.parse(JSON.stringify(oldObject));

Works well with your jsfiddle 与您的jsfiddle完美搭配

If you are using jquery in your project, you could use "jquery way" as well: 如果在项目中使用jquery,则也可以使用“ jquery方式”:

var newObject =  jQuery.extend(true, {}, oldObject);

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

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