JavaScript中的伪数组对象转化成数组的方法

首先什么是伪数组对象呢?
字面意思理解来说,伪数组对象就是长得像数组的对象,拥有0,1,2,3…以及length等key,但是在原型链中没有Array.prototype这一环,所以他没有操作数组的方法push,pop,shift,unshift等。javaScript中常见的伪数组对象有以nodeList为原型的DOM对象,函数的参数arguments对象等。

那么有没有方法将这些伪数组对象转换成数组,从而直接使用push,pop等方法来对其进行操作呢?
答案是肯定的。

var divTags = document.querySelectorAll('div')

ES5提供了一种方法:

var divTagsArray = Array.prototype.slice.call(divTags)
console.log('push' in divTagsArray)     //true

ES6提供了两种方法:

let divTagsArray1 = Array.from(divTags)
console.log('push' in divTagsArray1)  //true
let divTagsArray2 = [...divTags]
console.log('push' in divTagsArray2)  //true

猜你喜欢

转载自blog.csdn.net/m0_38102188/article/details/81327465