es6数组的扩展

1. 扩展运算符

应用
1.复制数组
const arr = [1, 3, 5]
const arr2 = [2, 4, 6]
(1)es5
const res = arr.concat()
console.log(res)  // [1, 3, 5]
const res2 = [...arr]
console.log(res2)  // [1, 3, 5]

2.合并数组
const res = arr.concat(arr2)
console.log(res)  // 1, 3, 5, 2, 4, 6
const res2 = [...arr, ...arr2]
console.log(res2)  // [1, 3, 5, 2, 4, 6]

3.与解构赋值混用
const [first, ...res] = [1, 2, 3, 4]
console.log(first)  // 1
console.log(res)  // [2, 3, 4]
const [second, ...res] = []
console.log(second)  // undefined
console.log(res) = []
const [third, ...rest] = ['foo']
console.log(third)  // foo
console.log(...rest)  // []

4.字符串
const str = 'hello'
const resStr = [...str]
console.log(resStr)  // ['h', 'e', 'l', 'l', 'o']

2. Array.form(参数1, 参数2, 参数3) 用于将两类对象转为真正的数组:类似数组的对象(array-like object)和可遍历(iterable)的对象(包括 ES6 新增的数据结构 Set 和 Map)

(1)参数1 想要转化的参数
const res = Array.form([1, 2, 3])
console.log(res)  // [1, 2, 3]
const res2 = Array.form('hello')
console.log(res2)  // ['h', 'e', 'l', 'l', 'o']
let arrayLike = {
'0': 'a',
'1': 'b',
'2': 'c',
length: 3
}
const res3 = Array.form(...arrayLike)
console.log(res3)  // ['a', 'b', 'c']
(2)参数2 ,可以相当于map、filter等函数,对参数1进行处理
const res4 = Array.form([1, 2, 3], x => x + 1)
console.log(res4)  // [2, 3, 4]
(3)参数3 如果map, filter里面有this,参数3可改变this指向

3. Array.of() 用于将一组数值转化为数组

(1)构造函数
const arr = new Array()  // []
const arr2 = new Array(3)  // [, , ,]
const arr3 = new Array(3, 8, 11)  // [3, 8, 11]
const arr4 = new Array(undefined)  // [undefined]
(2)Array.of()
const ar = Array.of()  // []
const ar2 = Array.of(3)  // [3]
const ar3 = Array.of(3, 8, 11)  // [3, 8, 11]
const ar4 = Array.of(undefined)  // [undefined]

4. Object.keys()、values()、entries() 分别是对键名、键值、键值对的遍历

const obj = {
        name: "slm",
        age: 11,
        gender: '男'
    }
for(const key of obj.keys()){
        console.log(key)  // name age gender
   }
for(const key of obj.values()){
        console.log(key)  // slm 11 男
   }
for(const key of obj.entries()){
        console.log(key)  // ["name", "slm"] ["age", 11] ["gender", "男"]
   }

5. Array.includes() 表示某个数组是否包含给定的值,回一个布尔值

const arr = [1, 3, 5]
const res = arr.includes(3)
console.log(res)  // true

6. Array.at() 找到索引对应的值

const arr = [1, 2, 3, 4, 6]
const res = arr.at(2)
console.log(res)  // 3
const res2 = arr.at(-1)
console.log(res2)  // 6
const res3 = arr.at(100)
console.log(res3)  // undefined //超出范围返回undefined
posted @ 2022-03-28 17:37  SKa-M  阅读(25)  评论(0编辑  收藏  举报