数组常用操作总结1

1创建数组

创建数组是基本功,其方法主要包括以下几种:

const arr = [1,2,3]                   // 数组字面量
const arr = [,,,]                     // 三元素空位数组(hole array)
const arr = new Array(4)              // [,,,,]
const arr = new Array(4,2)            // [4,2]
const arr = Array.of(1,2,3)           // [1,2,3]

2判断是不是数组

判断是不是数组的方法主要有:

// 方法一
[1,2,3] instanceof Array   
// 方法二
[1,2,3].constructor === Array
// 方法三
Object.prototype.toString.call([1,2,3]) === '[object Array]'
// 方法四
Array.isArray([1,2,3])
// 方法五(兼容写法)
function isArray(arr){
    return Array.isArray ? 
        Array.isArray(arr):Object.prototype.toString.call(arr) === '[object Array]'
}
复制代码

一般最常用的应该是 isArray 方法。

3类数组和数组的转换

我们有时碰到的数据结构不是纯数组,一般将其归类为“类数组”,类数组可以借助以下方法转为纯数组:

const x = document.querySelectorAll('a');
// 方法一
Array.prototype.slice.call(x);
// 方法二
Array.from(x);
Array.from(x,mapFn,thisArg);
// 方法三
[...x]
// 方法四
function toArray(x){
    let res = []
    for(item of x){
        res.push(item)
    }
    return res
}
// 方法五
Array.apply(null,x)
// 方法六
[].concat.apply([],x)
复制代码

方法五和六本质上都是利用了 apply 的特点,即传给 apply 的第二个参数(数组或者类数组)会被转换为一个参数列表,这些参数再送到调用的方法(new Array 或者 concat)中。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值