es6新增方法详解

1 数组新增方法

Array.of 定义数组
Array.from 把类数组转化为数组
Fill 用某个值替换数组的某一部分
Flat 把多维数组转化为一维数组
copyWithIn 拿数组的某一部分替换数组的另一部分
Includes 判断数组里是否有某一项 返回布尔值
Keys 拿到数组的所有键值
Values 拿得数组的所有value值
find 找到满足条件的第一个值

详解示例:
(1)Array.of (): 定义数组的另一种方法
例:

 {
            //定义数组的另一种方法:Array.of
            let arr=Array.of(1,2,3,"a","b");
            console.log(arr);

        }

(2)Array.from():把类数组转化为数组
例:

 var obj={
            2:"aa",
            3:"bb",
            length:5
        }        
        var arr1=Array.from(obj);//把类数组转化为数组
        console.log(arr1)   arr1=[undefined,undefined,"aa","bb",undefined];

(3)fill():填充替换数组
该函数有三个参数。

arr.fill(value, start, end)

value:填充值。
start:填充起始位置,可以省略。
end:填充结束位置,可以省略,实际结束位置是end-1。
例:

 {
            let arr=[1,2,3,4];
           console.log( arr.fill(0,1,2))
           arr=[1,0,3,4]
        }

(4)find():找到满足条件的第一个值
例:

 var arr=[1,2,3,4,5]
var res= arr.find(item=>{
       return item>3 
    })
    // 找到满足条件的第一个值 跟some的却别:some返回的是布尔值
    console.log(res);    res=4;

    {
        let arr=[{id:1,name:"小丽"},{id:2,name:"小明",num:3}];
        let res=arr.find(item=>{
            return item.id==2;
        })
        console.log(res); res={id:2,name:"小明",num:3}
        if(res){
            console.log("存在")      存在
        }

        let res2=arr.findIndex(item=>{
            return item.id==2
        })
        console.log(res2);  res2=1;
    }

find,findIndex和some的区别:
some() find() findIndex() 都是找某个东西在数组结构中存不存在
这几种可以查找复杂的数据类型

find some
find返回符合条件的数据 some返回布尔值

findIndex() 返回符合条件数据的下标
indexOf()也是查找 但是只能查找简单的数据类型

(5)values() keys():拿到数组的键值和value值
只能在循环里用
例:

   var arr=[1,2,3,4,5]
  {
            let arr=[3,4,5];
            console.log(arr.values().next())
            console.log({value:3,done:false})
        }

2 字符串新增方法

startsWith 判断字符串是否以谁开头
endsWith 判断字符串是否以谁结尾
repeat 重复字符串
padStart 头部补全
includes 查找参数字符是否存在 返回布尔值
padEnd 尾部补全

详解:
(1)padStart():在字符串前补全
两个参数: 第一个参数是补全之后字符串的长度,第二个参数是要拿什么去补
例:

  let num="1";
        num=num.padStart(2,"0");
        // 第一个参数是补全之后字符串的长度,第二个参数是要拿什么去补
        console.log(num); 
         // 在字符串前补0
        //num=01

(2)padEnd():在字符串尾部补全
两个参数: 第一个参数是补全之后字符串的长度,第二个参数是要拿什么去补
例:

  let num="1";
        num=num.padEnd(2,"0");
        // 第一个参数是补全之后字符串的长度,第二个参数是要拿什么去补
        console.log(num); 
         // 在字符串尾部补0
       //num=10

(3) repeat():重复字符串
例:

  let str="hello";
        console.log(str.repeat(3));
       //str=hellohellohello;

(4) includes():查找参数字符是否存在 返回布尔值
例:

let str="hello";
 console.log(str.includes("h"));
 //true

(5) includes() startswith() endswith() :
都有两个参数 第一个是查询的字符 第二个是开始查询的位置

你可能感兴趣的:(es6新增方法详解)