ES6数组&String API
数组
记录一下es6得数组方法,方便自己查阅!
类数组转换为数组
Array.from()
// 说白了这个函数就是遍历传入得类数组然后返回一个新得数组
var oDivs = document.querySelectorAll('div')
console.log(oDivs); //这是一个类数组对象
// 利用打散数组得方法
var arr = [...oDivs]
// 利用函数API得方法,参数1是伪数组,参数二是回调函数,可选值
var arr = Array.from(oDivs)
console.log(arr);
// 此时的arr就是数组了,可以使用数组家的方法了
// 创建类数组对象
var arrLike = {
"0":"1",
"1":"2",
"length":2
}
console.log(arrLike);
var arr1 = Array.from(arrLike,(item)=>{return item*2})
console.log(arr1);
Array.find()
// 找出第一个符合条件的成员,找到返回元素,找不到返回undefined
var arr = [
{
id:1,
name:"张三"
},
{
id:2,
name:"张啊三"
},
{
id:2,
name:"张a啊三a"
},
]
var res = arr.find((item,i,arr)=>{
// console.log(arr);
// console.log(i);
return item.id==2
})
console.log(res);
//{id:2,name:"张啊三"}
Array.findIndex()
// 找出第一个符合条件的成员的下标,找到返回下标,找不到返回-1
var arr = [1, 2, 3, 4, 5, 6]
let index = arr.findIndex(val => val > 3)
console.log(index); //3
Array.includes()
// 查看数组中是否包含参数
var a = [1,2,3].includes(2)
var b = [1,2,3].includes(5)
console.log(a); //true
console.log(b); //false
String相关
这里是字符串相关的。。。。
startsWith()
endsWith()
//startsWith 参数字符串是否在原字符串头部
//endsWith 参数字符串是否在原字符串尾部
let str = 'Hello Wrold!'
console.log(str.startsWith('Hello')); //true
console.log(str.endsWith('d!')); //false
repeat()
// 将原字符串重复n次
let r1 = 'x'.repeat(2) //xx
let r2 = 'hello'.repeat(2) //hellohello
set数据结构
// set类似于数组是一种数据结构,特点是里面的值是唯一的,不能重复
const s1 = new Set([1,2,3])
console.log(s1); //Set(3) {1, 2, 3}
// 当我们在set中传入重复的初始值,会被过滤掉
const s2 = new Set([1,2,1,2])
console.log(s2.size); //查看set数据的长度 2
// 利用set结构做数组去重的方法
const s3 = new Set(['s','a','b','s'])
const arr = [...s3]
console.log(arr);//['s', 'a', 'b']
set常用API
// add(val) 添加某个值,返回Set结构本身
// delete(value) 删除某个值,返回一个布尔值,表示是否删除成功
// has(value) 返回一个布尔值,表示该值是否为Set成员
// clear(value) 清除所有成员,无返回值
const s = new Set()
s.add(1)
s.add(2)
s.delete(2)
console.log(s.has(1));
// s.clear()
console.log(s);
const s2 = new Set([1,3,4,5,6,7])
s2.forEach((val)=>{
console.log(val);
})