在JavaScript函数改变数组转换功能之外阵列? [英] Changing array in JavaScript function changes array outside of function?
本文介绍了在JavaScript函数改变数组转换功能之外阵列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么两个脚本有什么不同?我想是第一次剧本,但在第二drawData()它改变了数据,它的怪异。谁能告诉我它为什么,以及如何解决它。谢谢!
VAR数据= [右];功能drawData(ARRS,类型){
如果(类型==百分比){
ARRS [0] =OMG
}
警报(数据[0]);}
drawData(数据);
drawData(数据百分比);
2日:
VAR数据=权利;功能drawData(ARRS,类型){
如果(类型==百分比){
ARRS =OMG
}
警报(数据);}
drawData(数据);
drawData(数据百分比);
解决方案
第一个变种会修改对象作为参数传递给函数(这恰好是数组)传递 - 所以这种变化被认为是外面的功能。第二变型分配新值,以功能参数(这恰好是参照阵列),但不改变数组本身。
why the two of scripts are different ? what i want is the 1st script ,but in the second drawData() it changes the data,it's weird. can anyone tell me why it's, and how to fix it. thank you!
var data = ["right"] ;
function drawData(arrs,type){
if(type=="percentage"){
arrs[0]="omg";
}
alert(data[0]);
}
drawData(data);
drawData(data,"percentage");
2nd:
var data = "right" ;
function drawData(arrs,type){
if(type=="percentage"){
arrs="omg";
}
alert(data);
}
drawData(data);
drawData(data,"percentage");
解决方案
First variant modifies object passed as parameter to function (which happens to be array) - so this change is seen outside function. Second variant assigns new value to function parameter (which happens to be reference to array) but does not change array itself.
这篇关于在JavaScript函数改变数组转换功能之外阵列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文