Skip to content
New issue

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

Math.max.apply() #24

Open
minhuaF opened this issue Jul 21, 2021 · 0 comments
Open

Math.max.apply() #24

minhuaF opened this issue Jul 21, 2021 · 0 comments

Comments

@minhuaF
Copy link
Owner

minhuaF commented Jul 21, 2021

终于有一个具体的示例让我能不用靠司机硬背applycall的区别了。

今天看到一段高级的代码,觉得有必要好好记录一下。大概就是下面这样的

const list = [].map(item => item.clientHeight);
const maxHeight = Math.max.apply(null, list);

哇,看完感觉又学到了奇奇怪怪的知识。(其实估计是比较菜...

能理解上面代码的意思,就是寻找数组中的最大值,但是Math.max.apply(null, list),这样的用法是第一次看到。

所以有2个疑问

  1. 为什么要用apply;
  2. 为什么apply的第一个参数是null;

调用已知知识库理解一下

  1. Math.max() 是用来查找最大值;
  2. Math.max() 的语法是 Math.max(value1[,value2, ...]),它不能接受数组形式的参数;
  3. apply 方法的第一个参数是调用者,是调用apply方法的对象指向,第二个参数是一个数据集合
  4. apply可以将一个数组默认地转换为一个参数列表,比如
[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的值。

在此处,并没有任何对象调用Math.max,如果有,只能算是全局对象,所以,需要设置成null,通俗点理解其实就是,此处不需要任何的对象调用这个方法,只需要帮忙执行并返回结果即可。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant