JS应用push时提示push is not a function
push() 方法可向数组的末尾添加一个或多个元素,并返回新的长度。为什么有时候会提示失效呢:如下用的时候function(){let num={};$.each(it,function(index,items){num.push(items['##'])})}这样会提示如下:num.push is not a function;原因是定义的时候把他定义成了对象,实际应用当中应该是这样的<s
文章共393字 · 阅读需要大约2分钟
一键AI生成摘要,助你高效阅读
问答
·
push() 方法可向数组的末尾添加一个或多个元素,并返回新的长度。
为什么有时候会提示失效呢:
先说第一种情况
如下用的时候
function(){
let num={};
$.each(it,function(index,items){
num.push(items['##'])
})
}
这样会提示如下:num.push is not a function;
原因是定义的时候把他定义成了对象,实际应用当中应该是这样的
<script type="text/javascript">
var arr = new Array(3)
arr[0] = "George"
arr[1] = "John"
arr[2] = "Thomas"
document.write(arr + "<br />")
document.write(arr.push("James") + "<br />")
document.write(arr)
</script>
所以前面错误的代码应当修改如下:
function(){
let num=[];
$.each(it,function(index,items){
num.push(items['##'])
})
}
/*或者改成下面这样*/
function(){
let num=new array(0);
$.each(it,function(index,items){
num.push(items['##'])
})
}
再说第二种情况
假如通过了前面的定义的用法,有时候也会出现提示push is not a function,这是什么原因呢
因为他除了往数组的末尾添加元素之外,还会改变数组的长度,返回数组的长度。我们用的时候一般会认为应当这样写:
array=array.push()
而这样写会把返回的长度赋给array,
所以正确的写法为:
array.push()
不必加array=
更多推荐
已为社区贡献1条内容
所有评论(0)