zoukankan      html  css  js  c++  java
  • ES6那些事半功倍的新特性(一)

    数组方面

    Array.from(xxx):把json格式字符串转换成数组;

    Array.of(x,x,x):负责把一堆文本或者变量转换成数组

    find( ):该方法为实例方法,就是以Array对象开头的,该方法有三个参数(value,index,arr);具体用法看代码

    let arr=[1,2,3,4,5,6,7,8,9];
    console.log(arr.find(function(value,index,arr){
        return value > 5;
    }))
    // 6
    find()

    fill( )实例方法:把数组进行填充并替换,也是有三个参数(填充变量,开始填充位置,填充到的位置);

    let arr=[0,1,2,3,4,5];
    arr.fill('es',2,5);
    console.log(arr); //[ 0, 1, 'es', 'es', 'es', 5 ]
    fill()

    for…of循环:数组遍历

    //简单遍历
    let arr=['e','s','6']
    for (let item of arr){
        console.log(item);  //e s 6
    }
    //遍历索引
    let arr1=['e','s','6']
    for (let index of arr1.keys()){
        console.log(index); //0 1 2
    }
    //遍历索引和内容
    let arr=['e','s','6']
    for (let [index,val] of arr.entries()){
        console.log(index+':'+val); //0:e  1:s  2:6
    } 
    

    entries( )实例方法:英文意思是:进入,入口处,入口权。它可以帮我们生成Iterator(迭代,游标)形式的数组,因此需要时我们可以用 list.next().value 来访问下一个值。

    除了用for of循环遍历数组,我们也可以用forEach,filter,some来进行遍历

    let arr=['e','s','6'];
    arr.forEach((val,index)=>console.log(index,val));
    /*
        输出如下:
         0 'e'
         1 's'
         2 '6'
    */
    let arr1=['E','C','M'];
    arr1.filter(x=>console.log(x));
    /*
      E
      C
      M
    */
    let arr2=['Y','R','Z'];
    arr2.some(x=>console.log(x));
    /*
     Y
     R
     Z
     */
    

      

    函数方面

    默认值:ES6函数的参数可以设置默认值的,例如如下代码是不会报错的。注意:如果再严令模式下,使用默认值是会报错的

    function add(a,b=1){
        return a+b;
    }
    console.log(add(1)); // 2
    

    主动抛出错误:ES6中直接用throw new Error( xxxx ),就可以抛出错误

    function add(a,b){
        if(a == 0){
            throw new Error(`This is error${new Date()}${3+3}`);
        }
        return a+b;
    }
    console.log(add(0,1)); // This is errorThu May 17 2018 14:52:23 GMT+0800 (中国标准时间)6
    

    箭头函数  注意:如果是函数体中有多行代码时,就需要用大括号“{}”括起来才行

    var add =(a,b=1) => a+b;
    console.log(add(1));

    解构赋值(非常强大)

    对象的函数解构,解构可以用来函数传参,从此不用像es5中的一个一个传值了。

    let json = {
        a:'e',
        b:'s',
        c:'6'
    }
    function fun({a,b,c}){
        console.log(a,b,c);
    }
    fun(json); //e  s  6
    

    数组的函数解构,用…进行解构赋值 

    let arr = ['e','s','6'];
    function fun(a,b,c){
        console.log(a,b,c);
    }
    
    fun(...arr);  //e s 6
    

    in   是用来判断对象或者数组中是否存在某个值的。下面代码中的a 或 0 指的是对象的健(key)或者数组的下标

    let obj={
        a:'e',
        b:'s'
    }
    console.log('a' in obj);  //true
    let arr1=['e','s'];
    console.log(0 in arr1);  // true
  • 相关阅读:
    实现自己的类加载时,重写方法loadClass与findClass的区别
    MQ中将消息发送至远程队列的配置
    IOS开发之控件篇UITabBarControllor第一章
    IOS开发-图片尺寸
    IOS开发之进阶篇第一章
    AStar算法(转载)
    GEF
    WizardDialog 进度条使用记录
    Struts2学习笔记-jsp中引用struts2框架
    Struts2学习笔记-基本结构
  • 原文地址:https://www.cnblogs.com/yinghuochongfighter/p/9050203.html
Copyright © 2011-2022 走看看