ES6 new features (two) the expansion method of built-in objects

table of Contents

First, the extension method of the String object

Second, the numerical expansion method

Third, the expansion method of the array

Fourth, the expansion method of the object object


-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

First, the extension method of the String object

  1.1. Template strings

    1.1.1. The template string is a new way to create a string in ES6, which is defined by backticks (backticks are generally above the tab key and below the esc key, and the keyboard layout is different in different locations).

    1.1.2. When creating a template string, you can use $ {} to  parse the variable , which is more flexible.

    1.1.3. The template string can be wrapped. If a newline is used when creating the template string, it will also be wrapped during output.

    1.1.4. Using the template string, you can use $ {method name ()} to call the function. The value displayed at the position where the function is called is the value returned by the function, or undefined if there is no return value.

1      // 1. Create a template string (defined in backticks) 2      let str = `I am a template      string` ;
 3 4 5 // 2. Use the template string to parse variables 6      let type = ` template`;
 7 let tmepStr = `I am $ {type}      string` ;
 8 console.log (tmepStr); // Output: I am the template string 9 10 11 // 3. Use the template string to wrap 12      let obj = {
 13          'id ': 1 ,
 14          ' name ':' 张三 ' ,
 15          ' age ': 12
 16     }
 17 18      let html =    
             
             
     

             
             
     
              
`
 . 19          <div> obj.id $ {} </ div>
 20 is          <div> obj.name $ {} </ div>
 21 is          <div> obj.age $ {} </ div>
 22 is          `;
 23 is      the console.log (html); // The line will also be changed when the console outputs 
24              
25              
26              
27      // 4. Use the template string to call the function 
28      let fn = () => {
 29          return '帅帅' ;
 30      }
 31              
32      let msg = `I am $ {fn ()}`;
 33      console.log (msg); // Output I am a handsome guy 
34              
35              
36      // If the called function has no return value, the output value is undefined
37      let fn = () => {
 38          console.log ('handsome guy' );
 39      }
 40      let msg = `I am $ {fn ()}`;
 41      console.log (msg); // The output is undefined    

  

  1.2. Instance methods startsWith () and endsWith ()

    1.2.1. StartsWith (value): Determine whether the string starts with value and return a Boolean value.

    1.2.2. EndsWith (value): Determine whether the string ends with value, and return a Boolean value.

    let str = 'Instance method of test string' ;
            
    // Use of startsWith () method 
    let tmp = str.startsWith ('test'); // true
            
    // The use of endsWith method 
    let tmp2 = str.endsWith ('instance'); // false

  

  1.3. The string repeat () method

    1.3.1. The repeat (n) method is used to repeat the original string n times and return a new string.

    //repeat()方法
    let str = `a`;
    let newStr = str.repeat(3);
    console.log(newStr);//aaa

 

 

二、数值的扩展方法

  2.1.  二进制表示法0b或者0B为前缀。

    //1.二进制的表示法 0b或者0B为前缀
    let num = 0b11101001;
    let num2 = 0B11101001;
    console.log(num);//233
    console.log(num2);//233
            

  2.2. 八进制表示法以0o或者0O为前缀。

    //2.八进制的表示法,以0o或者0O为前缀
    let num1 = 0o666;
    let num2 = 0O666;
    console.log(num1);//438
    console.log(num2);//438

 

  2.3. Number.EPSILON

    2.3.1. Number.EPSILON是ES6新增的一个误差常量,代表1与大于1的最小浮点数的差

 

        它的值接近于 2.220446049250313e-16  , 也就是2的-52次方。,这个值就是浮点数运算的误差范围,如果小于这个误差范围则判定为相等,如果大于这个误差范围则判定为不相等。

        举例:如果 a - b 的绝对值 < Number.EPSILON 那么就可以判定 a == b。

    //判断Number.EPSILON 与 2的-52次方是否相等
    console.log(Number.EPSILON == Math.pow(2,-52));//true
            
    console.log(Number.EPSILON);//2.220446049250313e-16
            
    //将EPSILON精确到小数点后20位            
    console.log(Number.EPSILON.toFixed(20));//0.00000000000000022204

      

      经典案例:0.1 + 0.2 != 0.3

     let num1 = 0.1 + 0.2;
    let num2 = 0.3;
    console.log(num1 == num2);//false

    //num1是两个浮点数相加,浮点数相计算是不精确的
    console.log(num1);//0.30000000000000004

    //计算出 0.1 + 0.2 - 0.3的值, 如果值大于误差常量则不相等
    let diff = num1 - num2;
    console.log(diff);//5.551115123125783e-17
    //让diff变量精确到小数点后20位, 与EPSILON常量相比较
    console.log(diff.toFixed(20) < Number.EPSILON);//false

    

  2.4. 最大/最小安全整数 

    安全整数:在JS中能够精确表示的整数,超过这个范围则无法精确表示这个整数

    2.4.1. 最大安全整数:Number.MAX_SAFE_INTEGER = 9007199254740991  (2的53次方 - 1)

    2.4.2. 最小安全整数:Number.MIN_SAFE_INTEGER = -9007199254740991 (2的-53次方 -1 的负数)

    2.4.3. Number.isInteger() :判断是否为整数。

    //Number.isInteger()判断是否为整数
    console.log(Number.isInteger(1));//true
    console.log(Number.isInteger(1.0));//true
    console.log(Number.isInteger(1.1));//false

    2.4.4. Number.isSafeInteger() 是否为安全整数。

    //Number.isSafeInteger()是否为有效值
                
    console.log(Number.isSafeInteger(9007199254740992));//false
             
    console.log(Number.isSafeInteger(-9007199254740992));//false
             
    console.log(Number.isSafeInteger(9007199254740991));//true
             
    console.log(Number.isSafeInteger(-9007199254740991));//true

    

    

三、数组的扩展方法

  3.1. Array.of():将一组参数当做元素形成数组,如果不传参数就是一个空数组。

    //Array.of() 将一组参数当做元素形成数组
    let arr = Array.of(1,2,3,4,5,6);
    console.log(arr);//[1, 2, 3, 4, 5, 6]
            
    //Array.of()不传参数,就是一个空数组
    let empty = Array.of();
    console.log(empty);// [ ]

 

 

 

  3.2. Array.from() :将伪数组(类数组)或者是集合转换成真正的数组

    //Array.from() 将伪数组(类数组)或集合转换成真数组
    //伪数组中每一行的第一个参数为数组的下标,不可随意更改
    let likeArr = {
        '0':'1',
        '1':'zhangsan',
        '2':'12',
    length:3
    }
            
    let newArr = Array.from(likeArr);
    console.log(newArr);// ["1", "zhangsan", "12"]
            
    //Array.from()方法还可以接受第二个参数,用于对每个元素进行处理将处理后的值放入返回的数组
    let newArr2 = Array.from(likeArr, item => item + '测试');//箭头函数(普通函数也可以)
    console.log(newArr2);// ["1测试", "zhangsan测试", "12测试"        

 

  

  3.3. 数组的遍历方法

    3.3.1. keys()遍历:取出数组中各个元素的下标。

    3.3.2. values()遍历:取出数组中各个元素的值。

    3.3.3. entries()遍历:取出数组中各个元素的下标和值。

    let arr = ['a','b','c'];
            
    //keys遍历:取出数组中各个元素的下标
    for(let index of arr.keys()){
        console.log(index);//下标:0 1 2
    }
            
    //values遍历:取出数组中各个元素的值
    for(let value of arr.values()){
        console.log(value);//a b c
    }
            
    //entries遍历:把数组中各个元素的下标和值都取出来
    for(let [index,value] of arr.entries()){
        console.log(index,value);//0 "a" | 1 "b" | 2 "c"
    }

  

  3.4. copyWithin():元素替换并返回一个新数组。

    //copyWithin()
    let arr = [1,2,3,4,5,6,7,8,9,10];
    let newArr = arr.copyWithin(0,5,8);
    console.log(newArr);// [6, 7, 8, 4, 5, 6, 7, 8, 9, 10]

    //第一个数组中的元素是1-10,
   //在copyWithin()方法中分别有三个参数,各自代表的作用如下:
   //第一个参数0:从数组的0下标开始替换,也就是第一个元素
   //第二个参数5:替换的值是原数组(arr)下标5的元素
   //第三个参数8:根据第二个参数的值,决定需要替换多少个元素,这里第二个参数是5,所以替换三个元素
   //整合一起意思就是:从原数组的第一个元素开始,替换三个元素,替换后的值是元素组从下标5开始到下标8结束,三个元素。

   

  3.5. find()/findIndex()方法

    3.5.1. find()方法:查找数组中第一个符合条件的元素,接收一个函数作为参数,返回符合条件的元素,如果没有找到符合条件的元素则返回undefined。

    let arr = [1,2,3,4,5,6];
            
    let value = arr.find( item => item > 3);//使用的是箭头函数,普通函数也可以
    let value2 = arr.find(function(item){return item >3});//与上面的箭头函数一样
    let value3 = arr.find(function(item){return item>6});
    console.log(value);// 4
    console.log(value2);// 4
    console.log(value3);//undefined

    

    3.5.2. findIndex()方法:查找数组中第一个符合条件的元素,接收一个函数作为参数,返回符合条件的元素的下标,如果没有找到符合条件的元素则返回-1。 

    //findIndex()方法
    let arr = [5,15,25,35];
    let index = arr.findIndex(item => item > 20);
    console.log(index);//返回下标:2

 

 

    

  3.6. includes()方法

    3.6.1. includes()方法:表示在数组中是否包含给定的值,返回布尔值。

 

    //includes()方法
    let arr = ['a','b','c','d'];
    console.log(arr.includes('a'));//true
    console.log(arr.includes('e'));//false

 

 

 

 

四、object对象的扩展方法

  4.1. 简洁表示法:

//简洁表示法
let o = 1;
let b = 'zhangsan';
let j = 12;
            
//es5创建object对象
let es5 = {
o:o,
b:b,
j:j
};
            
//es6创建object对象
let es6 = {
  o,
   b,
   j
};
console.log(es5);//{o: 1, b: "zhangsan", j: 12}
console.log(es6);//{o: 1, b: "zhangsan", j: 12}



  //ES5中创建的object对象如果有方法
  let es5_method = {
    hello:function(){
      console.log('ES5对象中的方法');
    }
  };
  

  //ES6中创建的object对象如果有方法
  let es6_method = {
    hello(){
      console.log("ES6对象中的方法");
    }
  }

  es5_method.hello();
  es6_method.hello();

 

 

 

 

  4.2. 属性表达式

    在ES5中创建object对象的属性,属性名称是固定死的,声明之后不能灵活的更改,在ES6中可以灵活地更改属性的名称。

 

    //属性表达式
    let a = 'properties';
            
    //在ES5中声明的属性名是固定死的
    let es5_obj = {
        a:'a'
    }
            
    let es6_obj = {
        [a]:'b'
    }
            
    console.log(es5_obj.a);//输出:a
    console.log(es6_obj.properties);//输出:b  这里的properties对应上面声明的a变量的值

 

    ES6声明的属性名[a]就代表着外面声明的a变量,用中括号包裹,属性名称随着外部a变量的值的变化而变化。

  

  4.3. Object新增方法

    4.3.1. Object.is()方法:判断两个值是否相等,返回布尔值,等价于 ===

    //Object.is()方法      Object.is()方法等价于 ===
    let flag = Object.is('123','123');
    console.log(flag);//true
            
    let basic = Object.is('','');
    let basic2 = '' === '';
    console.log(basic);//true
    console.log(basic2);//true
            
    let ref = Object.is([],[]);//判断引用类型,两个空数组
    let ref2 = [] === [];
    console.log(ref);//false 因为两个空数组其实引用的地址是不一样的
    console.log(ref2);//false

 

    4.3.2. entries()方法:遍历object对象中的成员。

    //object对象的entries
    let obj = {
            'id':1,
        'name':'zhangsan',
        'age':12,
        hello(){
            console.log("aaaa");
        }
    }
            
    //遍历object对象中的成员
    for(let [key,value] of Object.entries(obj)){
        console.log(key,value);
    }    

输出结果:

 

 

 

 

 

Guess you like

Origin www.cnblogs.com/zyonghua/p/12758132.html