最近发现数组的有些不常用的方法传参容易搞混,所以写篇文章加深下影响。
好记性,不如烂笔头,而键盘就是我的笔头。
![](https://img.haomeiwen.com/i5097943/e5bd7303139805fc.png)
Array私有属性
一、Array.from()
这个方法是ES6才引进的方法,这个方法可以将类数组或者可迭代对象转化为新数组,既然讲到类数组,这里就讲一下类数组对象的一些特性。
1.必须有length属性
2.属性是索引值
3.类数组对象不是数组,是对象,只是和数组类似,它不能调用数组的方法。
Array.from(arrayLike[, fn[, thisArg]]) // 类数组对象,可选回调,执行回调函数时的this对象
这里主要讲比较常用的前两个参数
类数组转数组实例有三种方法
- Array.from(arrObj)
let arr = [1,2]
let test = Array.from({'0': 1, '1': 2, "length": 2}, x => x + x) // [2,4]
let test2 = Array.from(arr, x => x + x) // [2,4]
- Array.prototype.slice.call(arrObj[, params])
let test = Array.prototype.slice.call({'0': 1, '1': 2, "length": 2}) // [2,4]
let test = Array.prototype.slice.apply({'0': 1, '1': 2, "length": 2}) // [2,4]
// 注意这里不用bind,是因为bind不会立即执行
- ES6扩展运算符(...)
如常用的 new Map() 、new Set() 、arguments等对象。
let xx = new Set([1,2,2])
console.log([...xx]) // [1,2] 还起到去重的效果
总结
Array.from()是全能的,而方法2和方法3还是具有局限性,但如果不是转化类对象,本人比较喜欢使用ES6的扩展运算符,简单而且可以对对象进行扩展,还是比较方便的。
let aa = {'a': 1, 'b': 2, 'd': 3}
let bb = {'a': 2, 'b': 2, 'c': 3}
let cc = { ...aa, ...bb }
console.log(cc) // {a: 2, b: 2, d: 3, c: 3}
// 对目标对象aa同元素进行覆盖
二、Array.isArray()
这个方法判断对象是否为数组,如果是则返回true,否则返回false。
以下是和instanceof 的区别
let vv = []
console.log(vv instanceof Object) // true
console.log(vv instanceof Array) // true
三、Array.of()
ES6的新方法,返回参数个数arguments的数组,相当于[...arguments]
Array.of(1,2) // [1,2]
网友评论