好的,我只是在做一个将所有内容从一个列表移到另一个列表的函数,完成后,它会自发地变得不确定。这样做没有充分的理由,但是不好的原因是什么呢?
来看
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??????
只是为什么 我只是在我的函数中定义了它。你怎么了(从字面上看,我没有看到)?
原因是您用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
变量。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句