ES6 常用1

https://www.cnblogs.com/ainyi/p/8537027.html(new copy)

https://blog.csdn.net/qq_36709020/article/details/80045500(new copy)
( (1)交换变量的值 )

[x, y] = [y, x];

( (2)从函数返回多个值

// 返回一个数组
function example() { return [1, 2, 3]; }

var [a, b, c] = example();
// 返回一个对象
function example() { return { foo: 1, bar: 2 }; }

var { foo, bar } = example();

( (3)函数参数的定义

// 参数是一组有次序的值 function f([x, y, z]) { ... } f([1, 2, 3]);
// 参数是一组无次序的值 function f({x, y, z}) { ... } f({z: 3, y: 2, x: 1});

( (4)提取JSON数据

var jsonData = { i

d: 42,

status: "OK",

data: [867, 5309]

};
let { id, status, data: number } = jsonData;
console.log(id, status, number); // 42, "OK", [867, 5309]

5

( (6)遍历MAP结构

var map = new Map();

map.set('first', 'hello');

map.set('second', 'world');


for (let [key, value] of map) {

console.log(key + " is " + value);

}

// first is hello

// second is world

4.7 includes(), startsWith(), endsWith()

includes():返回布尔值,表示是否找到了参数字符串。

startsWith():返回布尔值,表示参数字符串是否在源字符串的头部。

endsWith():返回布尔值,表示参数字符串是否在源字符串的尾部

var s = 'Hello world!';
s.startsWith('Hello') // true

s.endsWith('!') // true

s.includes('o') // true

4.8 repeat()

repeat方法返回一个新字符串,表示将原字符串重复n次。

4.9 padStart(), ,padEnd() ES7推出了字符串补全长度的功能。如果某个字符串不够指定长度,会在头部或尾部补全。padStart用于头部补全,padEnd用于尾部补全。

4.10 模板字符串

上面这种写法相当繁琐不方便,ES6引入了模板字符串解决这个问题。
$('#result').append(`

There are <b>${basket.count}</b> items in your basket, <em>${basket.onSale}</em> are on sale!

`);

上面代码中的模板字符串,都是用反引号表示。如果在模板字符串中需要使用反引号,则前面要用反斜杠转义。
var greeting = `\`Yo\` World!`;

如果使用模板字符串表示多行字符串,所有的空格和缩进都会被保留在输出之中。
$('#list').html(` <ul> <li>first</li> <li>second</li> </ul> `);
上面代码中,所有模板字符串的空格和换行,都是被保留的,比如<ul>标签前面会有一个换行。如果你不想要这个换行,可以使用trim方法消除它。
$('#list').html(` <ul> <li>first</li> <li>second</li> </ul> `.trim());

模板字符串中嵌入变量,需要将变量名写在${}之中。

模板字符串之中还能调用函数。

var mm=['ca','ni','mei']

function function_name(a,b,c) {
for (only of arguments) {
console.log(only)
}

}
function_name(mm,2,3);

//[ "ca", "ni", "mei"]
// 2
// 3

7 数组的扩展

 Array.from() Array.from方法用于将两类对象转为真正的数组

7.2 Array.of()

Array.of方法用于将一组值,转换为数组。
Array.of(3, 11, 8) // [3,11,8]

Array.of(3) // [3]

Array.of(3).length // 1


Array() // []

Array(3) // [, , ,]

Array(3, 11, 8) // [3, 11, 8]

7.3 数组实例的 数组实例的copyWithin()

数组实例的copyWithin方法,在当前数组内部,将指定位置的成员复制到其他位置(会覆盖原有成员),然后返回当前数组。也就是说,使用这个方 法,会修改当前数组。

7.4 数组实例的 数组实例的find()和 和findIndex()

数组实例的find方法,用于找出第一个符合条件的数组成员。它的参数是一个回调函数,所有数组成员依次执行该回调函数,直到找出第一个返回值 为true的成员,然后返回该成员。如果没有符合条件的成员,则返回undefined。

[1, 4, -5, 10].find((n) => n < 0) // -5

[1, 5, 10, 15].find(function(value, index, arr) {

return value > 9;

})

// 10

上面代码中,find方法的回调函数可以接受三个参数,依次为当前的值、当前的位置和原数组。

console.log([1,2,3].map(x => x * x))        正常输出

console.log([1,2,3].map(x => x * x);)       报错

原文地址:https://www.cnblogs.com/dianzan/p/8543133.html