码迷,mamicode.com
首页 > 其他好文 > 详细

ES6那些事半功倍的新特性(一)

时间:2018-05-17 16:01:21      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:lap   date()   新特性   技术分享   访问   直接   字符串转换   AC   pre   

数组方面

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 来访问下一个值。

函数方面

默认值: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

ES6那些事半功倍的新特性(一)

标签:lap   date()   新特性   技术分享   访问   直接   字符串转换   AC   pre   

原文地址:https://www.cnblogs.com/yinghuochongfighter/p/9050203.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!