[英]Why do I get error when I try to alert the length of the passed array to the function?
Why do I get error when I try to alert the length of the passed array to the function: Here is code: 当我尝试向函数传递传递的数组的长度时,为什么会出现错误:这是代码:
<div>
<button onclick = "CreatTable()">click me!</button>
</div>
<script type ="text/javascript">
var data = ['First Name', 'Last Name', 'Email'];
function CreatTable(data) {
alert(data.length);
}
</script>
In this row: 在这一行:
alert(data.length); alert(data.length);
I get this error: 我收到此错误:
TypeError: data is undefined TypeError:数据未定义
Why I get this error? 为什么会出现此错误? What I am doing wrong?
我做错了什么?
You are rebinding name data
to a function argument. 您正在将名称
data
重新绑定到函数参数。 And calling it without any arguments. 并在没有任何参数的情况下调用它。 Sure
data
is undefined. 确定
data
未定义。
function CreatTable() { //use scoped variable data.
alert(data.length);
}
<div>
<button onclick = "CreatTable()">click me!</button>
</div>
<script type ="text/javascript">
var data = ['First Name', 'Last Name', 'Email'];
function CreatTable() {
alert(data.length);
}
</script>
Either pass data
as an argument to CreatTable
, or remove it and it'll refer to the data
array you've defined. 要么将
data
作为CreatTable
的参数CreatTable
,要么将其删除,它将引用您定义的data
数组。
You're calling the function without an argument CreatTable()
您正在调用不带参数
CreatTable()
的函数
whereas your function definition takes data
as argument. 而您的函数定义将
data
作为参数。
Because data
is a global variable, just remove it from the function definition: 因为
data
是全局变量,所以只需将其从函数定义中删除:
write function CreatTable() {
编写
function CreatTable() {
instead of 代替
function CreatTable(data) {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.