js伪数组转数组

伪数组转数组

伪数组:

  1. 按索引方式储存数据
  2. 具有length属性
let arrLike = {
	0: ‘a’,
	1: ‘b’,
	2: ‘c’,
	length: 3
}

常见伪数组arguments、NodeList

ES5:

function test () {
	let args = [].slice.call(arguments)
	let imgs = [].slice.call(document.querySelectorAll('img'))
}

ES6:

function test () {
	let args = Array.from(arguments);
	let imgs = Array.from(document.querySelectorAll('img'));
}

Array.from

语法:Array.from(arrayLike[, mapFn[, thisArg]])
返回:一个新的数组实例。

参数 含义 必选
arrayLike 想要转换成数组的伪数组对象或可迭代对象 Y
mapFn 如果指定了该参数,新数组中的每个元素会执行该回调函数 N
thisArg 可选参数,执行回调函数 mapFn 时 this 对象 N

mapFn,让你可以在最后生成的数组上再执行一次 map 方法后再返回。
也就是说 Array.from(obj, mapFn, thisArg)
就相当于 Array.from(obj).map(mapFn, thisArg)

Array.from({length: 5}, (v, i) => i);
// [0, 1, 2, 3, 4]

你可能感兴趣的:(ES标准,es6,javascript)