考虑以下代码:
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
var globalList = Array();
globalList[0] = "Test";
globalList[1] = "Another Test";
async function coreFunc(promiseName, sleepTime) {
console.log("Started CoreFunc: "+promiseName);
var localList = globalList;
console.log("Length of local array: "+localList.length);
console.log("Length of global array: "+globalList.length);
if (promiseName != "Promise0") {
for (i = 0; i < localList.length; i++) {
console.log(localList[i]);
}
}
if (promiseName == "Promise0") {
var testList = new Array();
testList[0] = "Changed";
globalList = testList;
}
await sleep(sleepTime);
console.log("Length of local array: "+localList.length);
console.log("Length of global array: "+globalList.length);
console.log("Done with CoreFunc: "+promiseName);
}
async function testMultiplePromises() {
var thArray = Array();
for (i = 0; i < 4; i++) {
var pr = new Promise(resolve => coreFunc("Promise" + i, 3000));
thArray[i] = pr;
}
for (i = 0; i < thArray.length; i++) {
await thArray[i];
}
}
globalList是一个全局数组。当调用上述代码时,如下所示:
await testMultiplePromises();
代码进入一个无限循环。问题肯定在以下部分,我正在将全局变量重新初始化为某个不同的数组:
if (promiseName == "Promise0") {
var testList = new Array();
testList[0] = "Changed";
globalList = testList;
}
有没有一种方法可以将全局数据结构复制到局部变量,而不会导致索引越界或无限循环之类的问题?下面的代码肯定不起作用:
var localList = globalList;
应该做些什么来确保Promises要么得到旧的数组,要么得到新的数组?换言之,我如何确保coreFunc(Promise0(中更改全局数据结构的代码受到保护?
- 无限循环是由for循环上的全局
i
变量引起的。你应该这样打字
...
for (var i = 0; i < localList.length; i++) {
...
for (var i = 0; i < 4; i++) {
...
for (var i = 0; i < thArray.length; i++) {
...
- 到";保护";数组,你可以这样复制它
var localList = JSON.parse(JSON.stringify(globalList));
您的代码中存在一些问题。
var globalList = Array();
-此处缺少新关键字var localList = globalList;
-这不会创建数组的副本,它只是创建对外部数组的引用。因此,无论您在localList中更改什么,globalList中也会更改。试试这个:var localList = [...globalList];
。这将创建一个(浅(副本globalList = testList;
—此处相同
这里可以找到关于按值传递与按引用传递的详细信息。