Javascript Eval覆盖变量 [英] Javascript Eval overwriting variable
本文介绍了Javascript Eval覆盖变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
不明白为什么下面的代码会覆盖我的var arr.任何帮助表示赞赏.
Don't understand why the code below is overwriting my 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]
谢谢
推荐答案
由于在JavaScript中,对象是通过引用值传递的,而数组是对象.评估在这里无关紧要.这是在没有eval的情况下产生相同问题的代码:
Because in JavaScript, objects are pass by reference value and arrays are objects. The eval is irrelevant here. Here is code producing the same issue without 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]
这篇关于Javascript Eval覆盖变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文