ES6内置对象拓展

Array() 扩展运算符

扩展运算符可以将数组或者对象转为用逗号分隔的参数序列

let ary = [1, 2, 3]; 
...ary // 1, 2, 3 
console.log(...ary);
// 1 2 3,相当于下面的代码 console.log(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];

构造函数方法: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(arrayLike, item => item *2)//[2,4]

注意:如果是对象,那么属性需要写对应的索引

实例方法:find()

用于找出第一个符合条件的数组成员,如果没有找到返回undefined

let ary = [{ 
    id: 1, 
    name: '张三' 
}, {
    id: 2,
    name: '李四'
 }]; 
let target = ary.find((item, index) => item.id == 2);
//找数组里面符合条件 的值,当数组中元素id等于2的查找出来,注意,只会匹配第一个

实例方法:findIndex()

用于找出第一个符合条件的数组成员的位置,如果没有找到返回 -1
let ary = [1, 5, 10, 15]; 
let index = ary.findIndex((value, index) => value > 9); 
console.log(index); // 2

实例方法:includes()

判断某个数组是否包含给定的值,返回布尔值
[1, 2, 3].includes(2) // true 
[1, 2, 3].includes(4) // false

String 的扩展方法

模板字符串

ES6新增的创建字符串的方式,使用反引号定义

let name = `zhangsan`;
模板字符串中可以解析变量
let name = '张三'; 
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"

Set 数据结构

ES6 提供了新的数据结构 Set 。它类似于数组,但是成员的值都是唯一的,没有重复的值。

Set本身是一个构造函数,用来生成 Set 数据结构

const s = new Set();

 Set函数可以接受一个数组作为参数,用来初始化

const set = new Set([1, 2, 3, 4, 4]);//{1, 2, 3, 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 结构中的2值 
    s.has(1) // 表示 set 结构中是否有1这个值 返回布尔值 
    s.clear() // 清除 set 结构中的所有值 //注意:删除的是元素的值,不是代表的索引

 遍历

Set 结构的实例与数组一样,也拥有 forEach 方法,用于对每个成员执行某种操作,没有
返回值。
s.forEach(value => console.log(value))

おすすめ

転載: blog.csdn.net/weixin_59769148/article/details/120709140
おすすめ