我编写了洗牌数组的代码:
function shuffle(arr) {
for (i = 0; i < arr.length; i++) {
x = Math.floor(Math.random() * arr.length);
y = Math.floor(Math.random() * arr.length);
if (x === y) { //for dont change arr[i] with arr[i]!!!
continue;
}
temp0 = arr[x];
arr[x] = arr[y];
arr[y] = temp0;
}
return arr
}它正常工作。但是我的问题是,这个函数不是全局的,我用一个例子来解释它:
sampleArray=["a", "b", "c", "d"];
shuffle(sampleArray); //only run function
console.log (sampleArray); // output NOT shuffled. ==>> ["a", "b", "c", "d"]
console.log (shuffle(sampleArray)); //output shuffled. my be ["d", "a", "c", "b"] or ...在主代码中,我不能声明sampleArray嵌套在洗牌函数中.
发布于 2020-03-15 17:03:53
你的代码中有错误。长度不长。而且,由于数组是通过引用传递的,所以不需要返回
function shuffle(arr) {
for (i = 0; i < arr.length; i++) {
var x = Math.floor(Math.random() * arr.length);
var y = Math.floor(Math.random() * arr.length);
if (x === y) { //for dont change arr[i] with arr[i]!!!
continue;
}
temp0 = arr[x];
arr[x] = arr[y];
arr[y] = temp0;
}
}
sampleArray=["a", "b", "c", "d"];
shuffle(sampleArray);
console.log(sampleArray);
发布于 2020-03-15 16:59:18
let、const和var上下文
如果不使用let、const或var定义变量,则它们的作用域将被定义为全局变量。
在这里中有一个关于javascript变量和作用域的很好的教程。
但恢复:
let、const或var放在变量之前,变量定义将始终作为全局变量创建。var,那么变量将作为函数作用域创建。let,变量将被块作用域(介于两个{}之间)。const,则会应用相同的let规则,但有一个例外,即您不能为变量指定一个新的值。而且!
javascript中的数组之类的非permitive值被传递给作为引用的函数,这意味着如果在函数中更改任何数组值,原始变量也将更改为value (关于更多信息,https://medium.com/@TK_CodeBear/javascript-arrays-pass-by-value-and-thinking-about-memory-fffb7b0bf43此链接)。这就是为什么要更改sampleArray:因为您更改了引用shuffle函数中的sampleArray的arr变量。
示范时间!
要使其工作,您可以在深度复制函数中执行arr的arr操作,如下所示:
function shuffle(arr) {
//deep copy
const deepCopyArray = JSON.parse(JSON.stringify(arr));
for (i = 0; i < deepCopyArray.length; i++) {
x = Math.floor(Math.random() * deepCopyArray.length);
y = Math.floor(Math.random() * deepCopyArray.length);
if (x === y) { //for dont change arr[i] with arr[i]!!!
continue;
}
temp0 = deepCopyArray[x];
deepCopyArray[x] = deepCopyArray[y];
deepCopyArray[y] = temp0;
}
return deepCopyArray
}
sampleArray=["a", "b", "c", "d"];
shuffle(sampleArray); //only run function
console.log (sampleArray); // output NOT shuffled. ==>> ["a", "b", "c", "d"]
console.log (shuffle(sampleArray)); //output shuffled. my be ["d", "a", "c", "b"]
https://stackoverflow.com/questions/60695346
复制相似问题