在js中,数组是特殊的对象,凡是对象有的性质,数组都有,数组表示有序数据的集合,而对象表示无序数据的集合。

那伪数组是什么呢,当然它也是对象,伪数组一般具有以下特点:

  • 按索引方式存储数据;
  • 具有length属性;
  • 没有数组的push、shift、pop等方法;

function的arguments对象,还有getElementsByTagName、ele.childNodes等返回的NodeList对象,或者自定义的某些对象,这些都可以是伪数组。

我们可以通过以下几种方式将伪数组转换为标准数组:

1、使用Array.prototype.slice.call()或[].slice.call();

Array.prototype.slice.call({  
 0:"hello",  
 1:12,  
 2:true,  
 length:3  
});  
//["hello", 12, true] 

2、使用ES6中Array.from方法;

Array.from({  
 0:"hello",  
 1:12,  
 2:2013,  
 3:"大学",  
 length:4  
});  
//["hello", 12, 2013, "大学"]  

 

相关文章:

  • 2021-08-25
  • 2021-12-08
  • 2021-12-12
  • 2021-06-27
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-08-12
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-06
相关资源
相似解决方案