ES6常用的新特性

2021-02-25  本文已影响0人  Bonne_nuit

1.let和const定义变量
2.变量的结构赋值:

//数组的结构赋值
let[a,b,c]=[1,2,3];
//对象的解构赋值
let { foo, bar } = { foo: 'aaa', bar: 'bbb' };

3.字符串的遍历:

for (let item of 'hi') {
  console.log(item)
}
//h
//i

4.模板字符串:

$('#result').append(`
  There are <b>${basket.count}</b> items
   in your basket, <em>${basket.onSale}</em>
  are on sale!
`);

5.字符串的方法:

includes(), //字符串中包含某个字符串或字符,返回值为boolean类型
startsWith(),//字符串的头部包含某个字符串或字符,返回值为boolean类型
endsWith(), //字符串的尾部包含某个字符串或字符,返回值为boolean类型
'x'.repeat(3) // "xxx"   将字符串重复3次
'x'.padStart(5, 'ab') // 'ababx'  字符串头部加入指定字数的指定字符
'x'.padEnd(5, 'ab') // 'xabab' 字符串尾部加入指定字数的指定字符
const s = " abc ";
s.trimStart() // "abc  "   消除字符串头部空格
s.trimEnd() // "  abc"     消除字符串尾部空格

6.数值的方法:

Number.isFinite(), //数值是否为有限值,返回boolean
Number.isNaN()     //数值是否为NaN,返回boolean
Number.parseInt(),  //将数值转换为整数
Number.parseFloat(), //将数值转换为浮点数
Math.trunc(),       //去除数值的小数部分,返回整数部分
Math.sign() ,      //判断数值为正数,复数 或0
//参数为正数,返回+1;
//参数为负数,返回-1;
//参数为 0,返回0;
//参数为-0,返回-0;
//其他值,返回NaN。

7.函数参数的默认值:

//允许函数的参数有默认值
function log(x, y = 'World') {
  console.log(x, y);
}

8.rest参数(剩余参数):

//用户获取函数多余的参数
function add(...values) {
  
}
const sortNumbers = (...numbers) => numbers.sort();
//用...代替数组的apply方法:
// ES5 的写法
function f(x, y, z) {
  // ...
}
var args = [0, 1, 2];
f.apply(null, args);

// ES6的写法
function f(x, y, z) {
  // ...
}
let args = [0, 1, 2];
f(...args);

6.数组:

//合并数组:
const arr1 = ['a', 'b'];
const arr2 = ['c'];
const arr3 = ['d', 'e'];

// ES5 的合并数组
arr1.concat(arr2, arr3);
// [ 'a', 'b', 'c', 'd', 'e' ]

// ES6 的合并数组
[...arr1, ...arr2, ...arr3]
// [ 'a', 'b', 'c', 'd', 'e' ]

Array.of(3, 11, 8) // [3,11,8]          将一组数值转为数组
//数组的查找
find() 和 findIndex() ;

[1, 4, -5, 10].find((n) => n < 0)
// -5,        返回查找的值

[1, 5, 10, 15].findIndex(function(value, index, arr) {
  return value > 9;
}) // 2,     返回查找到值的index

7.对象

//ES6 允许字面量定义对象时,用方法二(表达式)作为对象的属性名,即把表达式放在方括号内。
let propKey = 'foo';

let obj = {
  [propKey]: true,
  ['a' + 'bc']: 123
};

//常用的对象遍历,其它的还有3种,但比较不常用
(1)for...in
(2)Object.keys(obj)

//对象的结构赋值
let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };
x // 1
y // 2
z // { a: 3, b: 4 }


//比较两个值是否相等
Object.is('foo', 'foo');
//合并对象
Object.assign()

//返回值的数组
const obj = { foo: 'bar', baz: 42 };
Object.values(obj)
// ["bar", 42]

//返回键和值的数组
const obj = { foo: 'bar', baz: 42 };
Object.entries(obj)
// [ ["foo", "bar"], ["baz", 42] ]

8.Symbol(表示独一无二的值)
是 JavaScript 语言的第七种数据类型,前六种是:undefined、null、布尔值(Boolean)、字符串(String)、数值(Number)、对象(Object)

let s = Symbol();

9.set和map

//去除数组的重复项
const set = new Set([1, 2, 3, 4, 4]);  // [1,2,3,4]

//遍历操作
let set = new Set(['red', 'green', 'blue']);

for (let item of set.keys()) {
  console.log(item);
}
// red
// green
// blue

for (let item of set.values()) {
  console.log(item);
}
// red
// green
// blue

for (let item of set.entries()) {
  console.log(item);
}
// ["red", "red"]
// ["green", "green"]
// ["blue", "blue"]

//对每个数组对象进行操作
let set = new Set([1, 4, 9]);
set.forEach((value, key) => console.log(key + ' : ' + value))
// 1 : 1
// 4 : 4
// 9 : 9

10.proxy Proxy 可以理解成,在目标对象之前架设一层“拦截”,外界对该对象的访问,都必须先通过这层拦截,因此提供了一种机制,可以对外界的访问进行过滤和改写。Proxy 这个词的原意是代理,用在这里表示由它来“代理”某些操作,可以译为“代理器”。

11.promise

//使用Promise包装了一个图片加载的异步操作。如果加载成功,就调用resolve方法,否则就调用reject方法
function loadImageAsync(url) {
  return new Promise(function(resolve, reject) {
    const image = new Image();
    image.onload = function() {
      resolve(image);
    };
    image.onerror = function() {
      reject(new Error('Could not load image at ' + url));
    };
    image.src = url;
  });
}

12.async异步加载
async函数返回一个 Promise 对象,可以使用then方法添加回调函数。当函数执行的时候,一旦遇到await就会先返回,等到异步操作完成,再接着执行函数体内后面的语句。

async function getStockPriceByName(name) {
  const symbol = await getStockSymbol(name);
  const stockPrice = await getStockPrice(symbol);
  return stockPrice;
}

getStockPriceByName('goog').then(function (result) {
  console.log(result);
});

13.class语法糖,用于定义类,constructor构造函数

14.export和import:export命令用于规定模块的对外接口,import命令用于输入其他模块提供的功能

1.
var firstName = 'Michael';
var lastName = 'Jackson';
var year = 1958;

export { firstName, lastName, year };


2.export function multiply(x, y) {
  return x * y;
};

以上只是部分,我在项目中用到的或者我认为会用到的一些ES6语法的新特性,用过的人都深有体会,ES6绝对比Js香,这篇文章是为了我自己能够梳理知识,同时也希望能帮助到刚入门的同学们。

上一篇下一篇

猜你喜欢

热点阅读