【JavaScript】19_数组的方法与bind函数

234 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第21天,点击查看活动详情

18、数组的方法

sort()

  • sort用来对数组进行排序(会对改变原数组)

  • sort默认会将数组升序排列 注意:sort默认会按照Unicode编码进行排序,所以如果直接通过sort对数字进行排序 可能会得到一个不正确的结果

  • 参数:

  • 可以传递一个回调函数作为参数,通过回调函数来指定排序规则 (a, b) => a - b 升序排列 (a, b) => b - a 降序排列

    forEach()

  • 用来遍历数组

  • 它需要一个回调函数作为参数,这个回调函数会被调用多次 数组中有几个元素,回调函数就会调用几次 每次调用,都会将数组中的数据作为参数传递

  • 回调函数中有三个参数: element 当前的元素 index 当前元素的索引 array 被遍历的数组

filter()

  • 将数组中符合条件的元素保存到一个新数组中返回
  • 需要一个回调函数作为参数,会为每一个元素去调用回调函数,并根据返回值来决定是否将元素添加到新数组中
  • 非破坏性方法,不会影响原数组

map()

  • 根据当前数组生成一个新数组
  • 需要一个回调函数作为参数, 回调函数的返回值会成为新数组中的元素
  • 非破坏性方法,不会影响原数组

reduce()

  • 可以用来将一个数组中的所有元素整合为一个值(累计值,可为累加,累乘之类的)
  • 参数:
  1. 回调函数,通过回调函数来指定合并的规则
  2. 可选参数,初始值
     <script>
         let arr = ["a", "c", "e", "f", "d", "b"]
         arr = [2, 3, 1, 9, 0, 4, 5, 7, 8, 6, 10]
 ​
         arr.sort((a,b) => a-b)
         arr.sort((a,b) => b-a)
 ​
         arr = ['孙悟空','猪八戒','沙和尚','唐僧']
 ​
         arr.forEach((Element,index,array) => {
             console.log(Element,index,array)//Element,放在前面打印时,没有单引号
         })
 ​
         arr.forEach((Element,index) => console.log(index,Element))//Element放在后面打印时,有单引号,作为一个整体
 ​
         arr = [1,2,3,4,5,6,7,8]
         //获取数组中的所有偶数
         let result = arr.filter((ele) => ele > 5)
         result = arr.map((ele) => ele * 2)
 ​
         arr = ['孙悟空','猪八戒','沙和尚']
         result = arr.map((ele) => '<li>' + ele + '</li>')
         console.log(result)
 ​
         arr = [1, 2, 3, 4, 5, 6, 7, 8]
 ​
         result = arr.reduce((a, b) => {
             /* 
                 1, 2
                 3, 3
                 6, 4
                 10, 5
             */
             // console.log(a, b)
 ​
             return a * b//累乘
         })
         // result = arr.reduce((a, b) => a + b, 10)
     </script>

19、bind函数

根据函数调用方式的不同,this的值也不同:

  1. 以函数形式调用,this是window
  2. 以方法形式调用,this是调用方法的对象
  3. 构造函数中,this是新建的对象
  4. 箭头函数没有自己的this,由外层作用域决定
  5. 通过call和apply调用的函数,它们的第一个参数就是函数的this
  6. 通过bind返回的函数,this由bind第一个参数决定(无法修改)

bind() 是函数的方法,可以用来创建一个新的函数

  • bind可以为新函数绑定this
  • bind可以为新函数绑定参数

箭头函数没有自身的this,它的this由外层作用域决定, 也无法通过call apply 和 bind修改它的this 箭头函数中没有arguments

     <script>
         function fn(a, b, c) {
             console.log("fn执行了~~~~", this)//此处的this代指下面的obj
             console.log(a, b, c)
         }
 ​
         const obj = {name:"孙悟空"}
 ​
         const newFn = fn.bind(obj,10,20,30)
         newFn()
 ​
 ​
         const arrowFn = () => {
             console.log(this)
         }
 ​
         // arrowFn.call(obj)
         const newArrowFn = arrowFn.bind(obj)
         newArrowFn()
 ​
         class MyClass{
             fn = () => {
                 console.log(this)
             }
         }
 ​
         const mc = new MyClass()
 ​
         // mc.fn.call(window)
     </script>