We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
终于有一个具体的示例让我能不用靠司机硬背apply和call的区别了。
apply
call
今天看到一段高级的代码,觉得有必要好好记录一下。大概就是下面这样的
高级
const list = [].map(item => item.clientHeight); const maxHeight = Math.max.apply(null, list);
哇,看完感觉又学到了奇奇怪怪的知识。(其实估计是比较菜...
能理解上面代码的意思,就是寻找数组中的最大值,但是Math.max.apply(null, list),这样的用法是第一次看到。
Math.max.apply(null, list)
所以有2个疑问
null
调用已知知识库理解一下
知识库
Math.max()
Math.max(value1[,value2, ...])
[param1, param2, param3] => param1, param2, param3
这里已经把apply的特性说明白了,就是apply方法能将数据的每一项,转换成参数的列表项。
var max = Math.max.apply(null, [3,2,5,3]) 等同于 var max = Math.max(3,2,5,3)
如果要自己代码编写获取数组中的最大值,常用的估计就是这样了
var getMath = (array) => { let max = array[0]; let len = array.length; for(let i = 1; i < len; i++) { max = Math.max(max, array[i]); } return max; }
看着就比较繁琐。
第一个疑问解决,其实就是使用apply的特性,能比较高效简单地获取到数组的最大值或者最小值。
那第二个问题,apply的第一个参数为什么是null?
对于apply的第一个参数:代表的是函数运行时this的值。
this
在此处,并没有任何对象调用Math.max,如果有,只能算是全局对象,所以,需要设置成null,通俗点理解其实就是,此处不需要任何的对象调用这个方法,只需要帮忙执行并返回结果即可。
Math.max
The text was updated successfully, but these errors were encountered:
No branches or pull requests
今天看到一段
高级
的代码,觉得有必要好好记录一下。大概就是下面这样的哇,看完感觉又学到了奇奇怪怪的知识。(其实估计是比较菜...
能理解上面代码的意思,就是寻找数组中的最大值,但是
Math.max.apply(null, list)
,这样的用法是第一次看到。所以有2个疑问
apply
的第一个参数是null
;调用已知
知识库
理解一下Math.max()
是用来查找最大值;Math.max()
的语法是Math.max(value1[,value2, ...])
,它不能接受数组形式的参数;apply
方法的第一个参数是调用者,是调用apply
方法的对象指向,第二个参数是一个数据集合;apply
可以将一个数组默认地转换为一个参数列表,比如这里已经把
apply
的特性说明白了,就是apply
方法能将数据的每一项,转换成参数的列表项。如果要自己代码编写获取数组中的最大值,常用的估计就是这样了
看着就比较繁琐。
第一个疑问解决,其实就是使用
apply
的特性,能比较高效简单地获取到数组的最大值或者最小值。那第二个问题,
apply
的第一个参数为什么是null
?对于
apply
的第一个参数:代表的是函数运行时this
的值。在此处,并没有任何对象调用
Math.max
,如果有,只能算是全局对象,所以,需要设置成null
,通俗点理解其实就是,此处不需要任何的对象调用这个方法,只需要帮忙执行并返回结果即可。The text was updated successfully, but these errors were encountered: