首页 > 技术文章 > ECMAScript 6的一些新特性2

carol1987 2016-05-25 12:22 原文

 

看下ES6数组的一些新特性, 把类数组转换为真正的数组

    'use strict';

    var aDiv = document.getElementsByTagName('div');

    var eles = Array.from( aDiv );

    console.log( eles );

 

同样的方法也可以转字符串

    'use strict';

    var str = 'abcd';

    var eles = Array.from( str );

    console.log( eles );

 

数组的实例方法arr.find()

    'use strict';

    /*
        arr.find()
        找出第一个符合条件的数组元素
        参数:
        1 回调函数
        2 回调函数内this的指向

        遍历整个数组,遍历过程中调用回调函数,如果回调函数的返回值为true,则返回当前正在遍历的元素

        如果所有元素都不符合条件则返回undefined
    */


    var arr = [1,2,3,4,5];

    var n = arr.find(function(value, index) {
        return value > 3;
    });

    console.log( n );

    // 只返回第一个符合的条件

 

实例方法arr.findIndex()

    'use strict';

    /*
        arr.findIndex()
        找出第一个符合条件的数组元素的位置
        参数:
        1、回调函数
        2、回调函数内this的指向

        遍历整个数组,遍历过程中调用回调函数,如果回调函数的返回值卫true,则返回该数组元素的位置

        如果所有元素都不符合条件则返回-1
    */


    var arr = [1,2,3,4,5];

    var n = arr.findIndex( function(value, index){

        return value > 2;

    } );
    
     console.log( n );

 

arr.fill();

    'use strict';

    /*
        arr.fill()
        
        用来填充数组
        参数:
        1、填充的内容
        2、起始位置
        3、结束位置

    */


    var arr = [1,2,3,4,5];

    arr.fill(6,2,4);
    
    console.log( arr );

 

for of 方法

/*
        for of 

        与for in类似,for in是遍历key值,for of是遍历value值

        可以遍历数组,字符串,但是不能遍历对象

    */


    var arr = [1,2,3,4,5];

    for(var value of arr){
        console.log( value );  // 1 2 3 4 5
    };

  // keys()方法

   var arr = [1,2,3,4,5];

   for(var key of arr.keys() ){
     console.log( key );
   };

 

   // 一起遍历(解构赋值)

   var arr = [1,2,3,4,5];

   for(var [key, value] of arr.entries() ){
     console.log( key, value );
   };

 

 

数组推导

    'use strict';

    /*
        数组推导

        ES6提供简洁写法,允许直接通过现有数组生成新数组,这被称为数组推导(array comprehension)

        貌似chrome不支持,用火狐就好了

    */

    var arr = [1,2,3];

    var arr2 = [for(value of arr) value * 2];

    console.log(arr2);

 

对象的简洁表示法

    /*
        对象的简洁表示法
    */

    function fn (x, y){
        
        x++;
        y++;

        return {x, y};
    };

    console.log( fn(1,2) );

  // 对象也有简洁写法

   var obj = {
     name : 'piaomiao',
     getName(){
       return this.name;
     }
   };

   console.log( obj.getName() );

/*
  也可以把名字用中括号括起来
*/

var sex = '男';

var person = {
  name : 'piaomiao',
  [sex] : false,
  ['get'+'Name'](){
    return this.name;
  }
};

console.log( person.getName() );

console.log( person[sex] );

 

对象另外的一些方法

    /*
        对象另外的一些方法
    */

    // 判断两个值是否相等 比===强大一点

  console.log( 0 === -0); // true
  console.log( Object.is(
0, -0) );  // false
  console.log(NaN, NaN);  // true

 

推荐阅读