Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

js apply Array方法的借用

 let arr1 =?[1,2,3]

 let arr2 =?[4,5,6]

 //????arr1.push(arr2)

 //????console.log(arr1)

 Array.prototype.push.apply(arr1,arr2)

 console.log(arr1)
 

在上述代码中,为了实现数组push的值为数组这种情况,采用的是Array.prototype.push.apply(arr1,arr2) 这样的方式。
imageimage

我在控制台打印了下下面两个方法,发现输出的方法都是一样的
既然arr1.push和Array.prototype.push的方法是一样的,为什么要借用Array.prototype.push这个方法呢?还有为什么Array.prototype.push这种方法可以实现数组push数组的功能,而arr本身的push方法却不能实现呢?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

因为 apply 方法接收一个数组作为参数

fn.apply(obj, [1,2,3])等同于obj.fn(1,2,3)

实际上,这种写法更多的见于祖传代码
现代js有可读性更好的写法

[1,2,3].push(...[4,5,6])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...