JS类数组转化为数组的三种方法
来源:互联网 发布:abb离线编程软件 编辑:程序博客网 时间:2024/05/29 09:34
一、类数组对象
定义:
- 拥有length属性,其它属性(索引)为非负整数
- 不具有数组所具有的方法
常见的类数组有arguments和NodeList,《javascript权威指南》里面给出了一个鉴别对象是否是类数组的函数:
// Determine if o is an array-like object.// Strings and functions have numeric length properties, but are // excluded by the typeof test. In client-side JavaScript, DOM text// nodes have a numeric length property, and may need to be excluded // with an additional o.nodeType != 3 test.function isArrayLike(o) { if (o && // o is not null, undefined, etc. typeof o === 'object' && // o is an object isFinite(o.length) && // o.length is a finite number o.length >= 0 && // o.length is non-negative o.length===Math.floor(o.length) && // o.length is an integer o.length < 4294967296) // o.length < 2^32 return true; // Then o is array-like else return false; // Otherwise it is not}
二、类数组转换为数组的方法
1、Array.prototype.slice.call()
这种方法是借用了数组原型中的slice方法,返回一个数组。slice方法的内部实现:
Array.prototype.slice = function(start,end){ var result = new Array(); start = start || 0; end = end || this.length; //使用call之后this指向了类数组对象 for(var i = start; i < end; i++){ result.push(this[i]); } return result; }
一个通用的转换函数:
var toArray = function(s){ try{ return Array.prototype.slice.call(s); } catch(e){ var arr = []; for(var i = 0,len = s.length; i < len; i++){ arr[i] = s[i]; } return arr; }
2、Array.from()
Array.from()是ES6中新增的方法,可以将两类对象转为真正的数组:类数组对象和可遍历(iterable)对象(包括ES6新增的数据结构Set和Map)。
var arrayLike = { '0':'a', '1':'b', '2':'c', length:3};var arr = Array.from(arrayLike);//['a','b','c']//把NodeList对象转换为数组,然后使用数组的forEach方法var ps = document.querySelectorAll('p');Array.from(ps).forEach(p){ console.log(p);}); //转换arguments对象为数组function foo(){ var args = Array.from(arguments); //...}//只要是部署了Iterator接口的数据结构,Array.from都能将其转换为数组Array.from('hello'); //['h','e','l','l','o']
3、扩展运算符(…)
同样是ES6中新增的内容,扩展运算符(…)也可以将某些数据结构转为数组
//arguments对象的转换function foo(){ var args = [...arguments];}//NodeList对象的转换[...document.querySelectorAll('p')]
扩展运算符实际上调用的是遍历器接口,如果一个对象没有部署此接口就无法完成转换
阅读全文
1 0
- JS类数组转化为数组的三种方法
- 伪数组转化为数组的方法
- javascript--类数组转化为数组方法
- 多维数组转化为一维数组---js方法
- js将数组对象转化为json格式的数组
- java 字符串转化为字符数组的3种方法
- js数组遍历的三种方法
- 多个数组转化为一个数组的方法
- java一维数组转化为二维数组的方法
- JS解析json数据并将json字符串转化为数组的实现方法
- JS解析json数据并将json字符串转化为数组的实现方法
- js中将类数组转换为数组的几种方法
- arrayToJson将数组转化为json格式的js代码
- js以逗号分隔的字符串怎么转化为数组
- js关联数组转化为json字符串
- js把字符串转化为对象、数组
- php解析数据格式转化为js数组
- java中把对象转化为byte数组的方法
- Java8-函数接口(Functional Interface)
- jdk8新特性
- C++ int ,float 与string 转换
- Android图片加载框架最全解析(四),玩转Glide的回调与监听
- oracle之运算符和表达式
- JS类数组转化为数组的三种方法
- 小程序导航的问题
- 使用multiprocesss模块进程通信采用队列方式,子进程run执行完一直不能退出的问题
- CSS实现文本显示部分内容,多余文本显示省略号
- Spring入门(基于Java的容器注解之@Scope和基于泛型的自动装配)
- 【Leetcode】【python】Pow(x, n)
- 【20170929】C语言每日一练
- jdk9新特性
- 国庆阅兵 我们阅代码!全球知名区块链底层技术对比