ES5/6的方法梳理

一、(数组相关)

(1)forEach(callback())方法

forEach里面回调函数有着三个参数:value, index, arr       
第一为数组的值,第二为数组每一个值对应的索引号,第三为原数组
遍历数组,作用:得到数组的值和索引号 
    let arr = [2, 4, 6, 8, 9];
    arr.forEach(function (value, index, arr) {//arr为数组本身
        console.log(value); //获取到数组每一个元素的值
        console.log(index); //获取到数组每一个元素的索引号
    })
    
eg:用forEach()方法循环精灵图
思路:一个ul里面包含9个li,然后在li的css样式之中,添加一个背景图url
    let lis = document.querySelectorAll('li');
    lis.forEach(function (value, index) {
        let i = index * 49 + 'px';//这边是y轴的移动距离
        lis[index].style.backgroundPosition = `0 -${i}`;
    })
    
eg:用forEach()方法进行排他思想处理
思路:先干掉所有人,留下自己,给自己做单独的样式
    let btns = document.querySelectorAll('button');
    btns.forEach(function (value, index) {
        btns[index].addEventListener('click', function () {
            btns.forEach(function (value, index) {
                btns[index].className = '';
            })
            this.className = 'bg';
        })
    })

(2)filter(callback())方法

filter里面回调函数有着三个参数:value, index, arr       
第一为数组的值,第二为数组每一个值对应的索引号,第三为原数组
遍历数组,根据指定的条件,返回一个新数组。作用:用于筛选数组
    let arr = [10, 3, 27, 40, 0, 1, 4, 4];
    let newArr = arr.filter(function (value) {
        return value >= 10;
    })
    console.log(newArr); //结果: [10, 27, 40];

()apply(thisArg,arr)方法

apply里面两个参数,第一个是指向那个对象,第二个代表接受数组形式
作用:用于数组中秋最大值,还可以改变函数内部的this指向
    let arr = [2, 4, 6, 8, 9];
    let max = Math.max.apply(Math, arr)
    console.log(max);//结果:9

() …arr 扩展运算符

作用:把数组或对象转化为逗号分割的参数序列,可以合并数组:
01:把数组转化为逗号分割的参数序列
    var arr = ['pink', 'red', 'yellow'];
    console.log(...arr); 结果:pink red yellow
02:合并两个数组
    var arr1 = [1, 3, 4];
    var arr2 = [6, 8];
    console.log([...arr1, ...arr2]);  结果:【1,3,4,6,8】

() Set数据结构

Set数据结构:它类似于伪数组,成员没有重复的值
作用:数组去重;
    var s = new Set([1, 3, 4, 22, 44, 1, 3, 0]);
    console.log([...s]);  结果:【1, 3, 4, 22, 44, 0】
Set涵盖add()方法等

()find(callback())方法

参数:function(currentValue, index,arr)   第一个为当前的值,第二个为对应的索引号,第三个为原数组
作用:找出第一个符合条件的数组元素
    var data = [{
            id: 1,
            name: 'red',
        },
        {
            id: 2,
            name: 'yellow'
        }
    ]
    let re = data.find((item, index) => {
        return item.id === 2
    })
    console.log(re);

()findIndex()方法

参数:function(currentValue, index,arr)   第一个为当前的值,第二个为对应的索引号,第三个为原数组
作用:用于查找数组中第一个满足条件的成员位置,返回到这个位置,若没有就返回-1
    let arr = [1, 3, 5, 7, 9];
    let index = arr.findIndex((value, index) => value >= 5);
    console.log(index);  结果:2

()includes()方法

参数:就是输入所要查找的值
作用:用于查找数组中是否包含这个值,返回的是一个布尔值
    let arr = [1, 3, 5, 7, 9];
    var re = arr.includes(3);
    console.log(re);   结果:true

二、(字符串相关)

(1)字符串的拼接:

    let str = 'pink老师';  //这边为模板字符串
    console.log(`你是我的老师啊${str}`);
    运用`${}`,来实现字符串的拼接  
    结果:你是我的老师啊pink老师
发布了8 篇原创文章 · 获赞 1 · 访问量 178

猜你喜欢

转载自blog.csdn.net/weixin_43845137/article/details/104675013