JavaScript,如何理解[].forEach.call()代码?
发布于 作者:苏南大叔 来源:程序如此灵动~
本文中讲述一个看上去稍稍有些烧脑的js
写法:[].forEach.call()
。如何理解这个看上去有些奇怪的js
写法呢?本文就是个类似孔乙己的茴香豆的hui字,有几种写法的问题。看起来高大上,细分析的话,就会发现这是个很无聊的写法而已。
大家好,这里是苏南大叔的程序如此灵动博客,这里记录苏南大叔的代码所学所想,本文描述一个比较罕见的茴香豆的hui字的写法的故事,代码的一个另类写法而已。测试环境:"谷歌浏览器@111.0.5563.111"。
代码主体
这里先提出代码的例子,大家猜一猜代码的运行效果是什么样的。
var arr = [];
[].forEach.call(["s", "u", "n", "a", "n"], function (item) {
arr.push(item);
});
console.log(arr);
运行结果是:
newsn.net:这里是【评论】可见内容
.call()
以前苏南大叔有篇文章,是分析.call()
的用法的,参考下面的链接:
基本的结论是:A.call()
基本上可以理解为A()
,但是.call()
可以修改this
指向。参考代码:
var sunan = {
c: 3,
test: function (a, b) {
return a + b + this.c;
}
}
console.log(sunan.test(1, 2)); // 6
console.log(sunan.test.call({ c: 4 }, 1, 2)); // 7
在这个例子里面,通过.call()
的第一个参数,成功的修改了this.c
属性。输出为:
6
7
.forEach()
对于.forEach()
,苏南大叔也有篇文章对其进行过分析。参考文章:
参考代码如下:
const arr2 = ["sunan", "苏南"];
arr2.forEach((val, key, arr) => {
console.log(val, key, arr);
});
不管是set
类型,还是array
类型,或者是map
类型,都存在着forEach
方法,除了key
有所不同外,其它的两个参数都一致。本例子的输出为:
sunan 0 (2)?['sunan', '苏南']
苏南 1 (2)?['sunan', '苏南']
[].forEach.call()
再回到文章顶部的代码,这个代码究竟是个什么意思呢?运行结果是什么样的呢?看完代码的运行结果的话,就会发现这个大费周折的代码的运行结果,其实就是做了一个变量的定义而已。
var arr = [];
[].forEach.call(["s", "u", "n", "a", "n"], function (item) {
arr.push(item);
});
console.log(arr);
上面的这个就相当于:
var arr = ["s", "u", "n", "a", "n"];
相关链接
- https://newsn.net/say/js-set.html
- https://newsn.net/say/js-map.html
- https://newsn.net/say/js-call.html
- https://newsn.net/say/js-apply.html
- https://newsn.net/say/js-bind.html
总结
茴香豆的hui字有几种写法呢?脱去长衫的孔乙己也许更不知道。


