javascript - 为什么函数一结束我的数组就变得未定义?
问题描述
好的,我只是在做一个将所有内容从一个列表移动到另一个列表的函数,一旦完成,它就会自发地变得未定义。它没有很好的理由这样做,但什么是不好的理由?
来,看,
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
变量。
推荐阅读
- google-chrome-extension - Vue Devtools 落后于应用程序事件
- odoo - 如何修改脚手架命令的文件和文件夹结构?
- c# - 如何在 C# 中将变量从一种形式导出/导入到另一种形式?
- c# - .NET 5.0 中的 Microsoft.VBE 参考不可用
- microsoft-graph-api - 仅限应用令牌 - Microsoft Graph - 首选语言
- node.js - Nodejs如何使用ajax发送经过身份验证的请求
- database-design - 将计算值用作聚合表中的维度是个坏主意吗?
- c++ - 在头文件中找不到“torch/torch.h”文件
- rxjs - 用 ConcatMap 替换 SetTimeout
- laravel - 由于依赖关系,将 Laravel 更新到 7x 失败,composer update -w 不起作用