ES6的内置对象扩展
一、Array 的扩展方法
扩展运算符(展开语法)
扩展运算符可以将数组或者对象转为用逗号分隔的参数序列
输出结果没有逗号,因为被当成参数分隔符
let ary = [ 1, 2, 3];
...ary // 1, 2, 3
console.log(...ary); // 1 2 3
扩展运算符可以应用于合并数组
// 方法一
let ary1 = [1, 2, 3];
let ary2 = [3, 4, 5];
let ary3 = [...ary1, ...ary2];
//方法二
ary1.push(...ary2);
将类数组或可遍历对象转换为真正的数组
let oDivs = document.getElementsByTagName('div');
oDivs = [...oDivs];
实例方法:find()
用于找出第一个符合条件的数组成员,如果没有找到返回undefined
let ary = [{
id: 1,
name: '张三'
}, {
id: 2,
name: '李四'
}];
let target = ary.find((item, index) => item.id == 2);
实例方法:findIndex()
用于找出第一个符合条件的数组成员的位置,如果没有找到返回 -1
let ary = [1, 5, 10, 15];
let index = ary.findIndex((value, index) => value > 9);
condole.log(index); // 2
实例方法:includes()
表示某个数组是否包含给定的值,返回布尔值。
[1, 2, 3].includes(2) // true
[1, 2, 3].includes(4) // false
构造函数方法:Array.from()
将类数组或可遍历对象转换为真正的数组
let arrayLike = {
'0': 'a',
'1': 'b',
'2': 'c',
length: 3
};
let arr2 = Array.from(arrayLike); // ['a', 'b', 'c']
方法还可以接受第二个参数,作用类似于数组的map方法,用来对每个元素进行处理,将处理后的值放入返回的数组
let arrayLike = {
"0": 1,
"1": 2,
"length": 2
}
let newAry = Array.from(aryLike, item => item * 2)
二、String 的扩展方法
模板字符串
ES6新增的创建字符串的方式,使用反引号定义
let name = `zhangsan`;
模板字符串中可以解析变量
let name = 'zhangsan';
let sayHello = `hello,my name is ${name}`; // hello,my name is zhangsan
模板字符串中可以换行
let result = {
name: 'zhangsan',
age: 20,
sex: '男'
}
let html = `
<div>
<span>${ result.name }</span>
<span>${ result.age }</span>
<span>${ result.sex }</span>
</div>
`
在模板字符串中可以调用函数
const sayHello = function(){
return '哈哈哈哈'
};
let greet = `${ sayHello() } 追不到我吧`
console.log(greet); // 哈哈哈哈 追不到我吧
实例方法: startsWith() 和 endsWith()
- startsWith():表示参数字符串是否在原字符串的头部,返回布尔值
- endsWith():表示参数字符串是否在原字符串的尾部,返回布尔值
let str = 'Hello world';
str.startsWith('Hello') //true
str.endsWith('!') //true
实例方法:repeat()
repeat方法表示将原字符串重复n次,返回一个新字符串
'x'.repeat(3) // "xxx"
'hello'.repeat(2) // "hellohello"
三、数据结构
ES6 提供了新的数据结构Set。它类似于数组,但是成员的值都是唯一的,没有重复的值
Set 本身是一个构造函数,用来生成 Set 数据结构
const s = new Set();
Set 函数可以接受一个数组作为参数,用来初始化
const set = new Set([1, 2, 3, 4, 5, 4]);
会把重复的值过滤掉,可以利用这个进行数组去重,输出的数组是去重之后的
实例方法
- add(value):添加某个值,返回 Set 结构本身
- delete(value):删除某个值,返回一个布尔值,表示删除是否成功
- has(value): 返回一个布尔值,表示改值是否为 Set 的成员
- clear():清除所有成员,没有返回值
const s = new Set();
s.add(1).add(2).add(3); // 向 set 结构中添加值
s.delete(2) //删除 set 结构中的值
s.has(1) //表示 set 结构中是否有1这个值 返回布尔值
s.clear() 清除 set 结构中的所有值