我定义了一个全局变量数组:
var redgather=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33];
然后在运行程序中引用了这个数组;
let temp=redgather;
当修改了temp的值的时候,redgather的值也被改变了;
而且temp是写在for循环中的,但是temp的值始终保持每一次被修改后的值。
原因出在:像let temp=redgather;这种赋值方式是传递的redgather的地址,修改temp的时候修改的是地址中的值,所以redgather的值会被改变。
代码如下:
var redgather=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33];
function test(){
let temp=redgather;
let outnums=[];
let max=33;
for(let i=0;i<6;i++){
let takeindex=Math.floor(Math.random()*max);
//console.log("takeindex======"+takeindex);
outnums.push(temp[takeindex]);
temp.splice(takeindex,1);
max--;
}
let bluenum=Math.floor(Math.random()*16)+1;
outnums.push(bluenum);
return outnums;
}
下次避免同类错误,取全局变量的值避免直接取。
例如:
let xx=[1,2,3,4,5,6,7,8,9];
let tpred=new Array();
for(let j=0;j<xx.length;j++){
tpred.push(xx[j]);
}