可以'无论我做什么,都无法访问函数外的数组
can't access array outside a function no matter what I do
这是html部分:
<form>
<input id="input" type="text"/>
<button id="button"> Add! </button>
</form>
<div class="list"></div>
脚本是这样的:
var input = document.getElementById("input"); // save the object
var button = document.getElementById("button");
var myArray = [];
button.onclick = function alerted (){
myArray.unshift(input.value); // get the value
return myArray;
};
alerted();
document.write(myArray);
问题是,无论我做什么,myArray总是保持原来的空数组。我希望得到启发,谢谢!
您必须使用为函数分配的变量的名称,在这种情况下button.onclick()
即可。命名函数表达式允许您在正文中使用名称,但必须使用引用名称,而不是函数名称才能在其他地方调用它。
button.onclick = function alerted() {
myArray.unshift(input.value); // get the value
return myArray;
};
button.onclick();
这样想吧——你把一个函数对象分配给一个变量——这个函数对象可能有名字,也可能没有名字(匿名)。因此,如果你的函数有一个名称,你可以这样显示:
button.onclick.name //=> alerted
以下内容:
button.onclick = function alerted (){
myArray.unshift(input.value); // get the value
return myArray;
};
将命名函数表达式指定给按钮的单击处理程序。函数应该只能通过函数内提醒的名称来使用。不幸的是,IE在这方面被破坏了(实际上jScript被破坏了),并使其可以作为全局变量使用。
您可能应该使用一个函数表达式:
function alerted (){
myArray.unshift(input.value); // get the value
return myArray;
}
button.onclick = alerted;
只有当单击按钮时,成员才会被添加到数组中,在此之前,它将为空。最初输入没有值,因此单击按钮(或调用函数)只会添加空字符串。
我包含window.onload,这样我们就可以假设输入和按钮不是空
window.onload = function(){
var input = document.getElementById("input"); // save the object
var button = document.getElementById("button");
var myArray = ["hello"];
button.onclick = function(){
myArray.unshift(input.value); // get the value
document.write(myArray);
};
}
相关文章:
- 访问函数外部的变量
- 从嵌套函数访问函数属性
- 访问函数对象的上下文属性|如何
- jQuery 无法使用 AJAX 调用访问函数内部的函数参数
- 访问函数中的函数名称
- 访问函数'的属性
- 访问函数内部的Polymer方法
- 从另一个文件访问函数的返回值
- 如何从AngularJS外部访问函数
- 如何在 JavaScript 中访问函数中的其他属性值作为对象属性值
- 从require()'d文件访问函数
- 如何访问函数中的变量
- JavaScript 访问函数构造函数中的“this”
- 跨不同作用域访问函数
- 访问函数内部的变量
- jQuery插件+AMD=如何访问函数
- 如何在javascript中访问函数内部的相同变量名
- 可以'无论我做什么,都无法访问函数外的数组
- 如何从module.exports访问函数
- 无法't访问函数中的对象