首页 > 解决方案 > 为什么函数一结束我的数组就变得未定义?

问题描述

好的,我只是在做一个将所有内容从一个列表移动到另一个列表的函数,一旦完成,它就会自发地变得未定义。它没有很好的理由这样做,但什么是不好的理由?

来,看,

function moveList(){//in my real program it actually shuffles the list, this one just transfers the contents
    var listOne=[0, 1, 2, 3];//we have a list
    var listTwo=[];//now we have an empty list
    var length = listOne.length//and now we have the list length
    for (run = 0; run < length; run++) {
        listTwo.push(listOne[0]);//it just copies the first entry from the first list to the second
        listOne.splice(0, 1,)//and deletes it from the first list
    }//this does it for an entry in the list, it's length amount of times
    console.log("listTwo: " + listTwo);//this tells us what the new list now is, and it works
    console.log("listOne: " + listOne);//this tells us what the original list is, which is empty
}
var listOne;
var listTwo;
//these are mandatory, without this, even with the function below script,
//you have Uncaught ReferenceError: list(One and Two) is not defined
moveList();//now we do the function, and then,
console.log("listTwo: " + listTwo);//THE LIST IS NOW UNDEFINED??? What??????

只是为什么?我实际上只是在我的函数中定义了它。你怎么了(字面意思,我不明白)?

标签: javascriptarraysfunction

解决方案


原因是您使用listTwo不同范围的名称初始化了两个列表!一个在全局范围内,你没有给它一个值,所以它保持undefined,另一个在函数内,并且不能从函数外部访问,因为已经有另一个同名的变量!

为了使您的代码正常工作,您应该使用函数内部的变量而不声明它们。

function moveList(){//in my real program it actually shuffles the list, this one just transfers the contents
    listOne=[0, 1, 2, 3];//we have a list
    listTwo=[];//now we have an empty list
    var length = listOne.length//and now we have the list length
    for (run = 0; run < length; run++) {
        listTwo.push(listOne[0]);//it just copies the first entry from the first list to the second
        listOne.splice(0, 1,)//and deletes it from the first list
    }//this does it for an entry in the list, it's length amount of times
    console.log("listTwo: " + listTwo);//this tells us what the new list now is, and it works
    console.log("listOne: " + listOne);//this tells us what the original list is, which is empty
}
var listOne;
var listTwo;

moveList();//now we do the function, and then,
console.log("listTwo: " + listTwo);//THE LIST IS NOW NOT UNDEFINED ;)

这同样适用于listOne变量。


推荐阅读