美文网首页
call,apply,bind的实际应用

call,apply,bind的实际应用

作者: 你喜欢吃青椒吗_c744 | 来源:发表于2019-07-29 16:24 被阅读0次

    call,apply,bind详解传送门

    求数组中的最大和最小值

    var arr = [34,5,3,6,54,6,-67,5,7,6,-8,687];
    Math.max.apply(Math, arr);
    Math.max.call(Math, 34,5,3,6,54,6,-67,5,7,6,-8,687);
    Math.min.apply(Math, arr);
    Math.min.call(Math, 34,5,3,6,54,6,-67,5,7,6,-8,687);
    console.log(Math.max.apply(Math, arr));
    console.log(Math.min.apply(Math, arr));
    
    

    将伪数组转化为数组

    js中的伪数组(例如通过document.getElementsByTagName获取的元素)具有length属性,并且可以通过0、1、2…下标来访问其中的元素,但是没有Array中的push、pop等方法。我们可以利用call、apply来将其转化为真正的数组这样便可以方便地使用数组方法了。

    var arrayLike = {
      0: 'qianlong',
      1: 'ziqi',
      2: 'qianduan',
      length: 3
    }
    

    上面就是一个普通的对象字面量,怎么把它变成一个数组呢?最简单的方法就是:

        
    var arr = Array.prototype.slice.call(arrayLike);
    

    上面arr便是一个包含arrayLike元素的真正的数组啦( 注意数据结构必须是以数字为下标而且一定要有length属性 )

    数组追加

    在js中要往数组中添加元素,可以直接用push方法

    var arr1 = [1,2,3];
    var arr2 = [4,5,6];
    [].push.apply(arr1, arr2);
    // arr1 [1, 2, 3, 4, 5, 6]
    // arr2 [4,5,6]
    

    判断变量类型

    对于对象型的数据类型,我们可以借助call来得知他的具体类型,例如数组

    function isArray(obj){
      return Object.prototype.toString.call(obj) == '[object Array]';
    }
    isArray([]) // true
    isArray('qianlong') // false
    

    相关文章

      网友评论

          本文标题:call,apply,bind的实际应用

          本文链接:https://www.haomeiwen.com/subject/mbibrctx.html