简体   繁体   English

Javascript Eval覆盖变量

[英]Javascript Eval overwriting variable

Don't understand why the code below is overwriting my var arr. 不明白为什么下面的代码会覆盖我的var arr。 Any help appreciated. 任何帮助表示赞赏。

var arr = [1,2,3]

var string = "function swap(arr) { var newarr = arr; var temp = arr[0]; newarr[0] = arr[arr.length-1]; newarr[arr.length-1] = temp; return newarr }"

var test = eval("[" + string + "]")[0];

test(arr);
console.log(arr);
//this outputs [3,2,1]

test(arr);
console.log(arr);
//this outputs [1,2,3]

fiddle 小提琴

Thanks 谢谢

Because in JavaScript, objects are pass by reference value and arrays are objects. 因为在JavaScript中,对象是通过引用值传递的,而数组是对象。 The eval is irrelevant here. 评估在这里无关紧要。 Here is code producing the same issue without eval: 这是在没有eval的情况下产生相同问题的代码:

var arr = [1,2,3];
var arr2 = arr; // this just sets the reference
arr2[1] = 3; // this also changes arr
arr[0] = 3; // this also changes arr2
arr; // [3, 3, 3]
arr2; // [3, 3, 3]

Why does this happen 为什么会这样

JavaScript kind of has a thing where it creates references instead of copies. JavaScript有点用它来创建引用而不是副本。 This can be useful, and annoying: 这可能很有用,而且很烦人:

Where is it useful? 在哪里有用?

var self = this;

is a commonly used trick to trap the scope of a function. 是捕获函数范围的常用技巧。

var elem = document.getElementById('my_element');

is a way refer to elements as variables 是一种将元素称为变量的方式

When does this happen? 什么时候发生?

var arr = [1, 2, 3, 4];

var arr2 = arr;    //arr2 now references arr
var arr2[1] = 'd'; //Modifies arr2 and reference

console.log(arr2); //Line 6
console.log(arr);  //Line 7

This will give us: 这将给我们:

[1, 'd', 3, 4] (line 6) [1,'d',3、4](第6行)

[1, 'd', 3, 4] (line 7) [1,'d',3,4](第7行)

In conclusion, this is just regular behavior of JavaScript! 总之,这只是JavaScript的常规行为!

What should I do? 我该怎么办?

To solve this, add 要解决此问题,请添加

var arr2 = arr.slice();

.slice() returns a new version of the array. .slice()返回数组的版本。 You can write your own function to do this by: 您可以通过以下方式编写自己的函数来执行此操作:

Array.prototype.clone = function () {
    return this.slice();
}

Now we can do: 现在我们可以做:

var arr = [1, 2, 3, 4];

var arr2 = arr.clone(); //  Returns cloned arr
var arr2[1] = 'd';      //  Modifies arr2

console.log(arr2); //Line 6
console.log(arr);  //Line 7

This time: 这次:

[1, 'd', 3, 4] (line 6) [1,'d',3、4](第6行)

[1, 2, 3, 4] (line 7) [1,2,3,4](第7行)

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

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