判断数组

之前有讲过数组去重的方法,今天说一下如何判断是否为空数组和数组的一些方法。话不多说直接上代码!

如何判断一个变量是不是数组:

使用 Array.isArray 判断,如果返回 true, 说明是数组;
使用 instanceof Array 判断,如果返回 true, 说明是数组;
使用 Object.prototype.toString.call 判断,如果值是 [object Array], 说明是数组;
通过 constructor 来判断,如果是数组,那么 arr.constructor === Array. (不准确,因为我们可以指定 obj.constructor = Array)

1
2
3
4
5
6
7
8
9
10
11
12
13
function fn() {
console.log(Array.isArray(arguments)); //false; 因为 arguments 是类数组,但不是数组
console.log(Array.isArray([1, 2, 3, 4])); //true
console.log(arguments instanceof Array); //fasle
console.log([1, 2, 3, 4] instanceof Array); //true
console.log(Object.prototype.toString.call(arguments)); //[object Arguments]
console.log(Object.prototype.toString.call([1, 2, 3, 4])); //[object Array]
console.log(arguments.constructor === Array); //false
arguments.constructor = Array;
console.log(arguments.constructor === Array); //true
console.log(Array.isArray(arguments)); //false
}
fn(1, 2, 3, 4);

数组方法

  • map: 遍历数组,返回回调返回值组成的新数组
  • forEach: 无法 break,可以用 try/catch 中 throw new Error 来停止
  • filter: 过滤
  • some: 有一项返回 true,则整体为 true
  • every: 有一项返回 false,则整体为 false
  • join: 通过指定连接符生成字符串
  • sort(fn) / reverse: 排序与反转,改变原数组
  • concat: 连接数组,不影响原数组, 浅拷贝
  • slice(start, end): 返回截断后的新数组,不改变原数组
  • splice(start, number, value…): 返回删除元素组成的数组,value 为插入项,改变原数组
  • indexOf / lastIndexOf(value, fromIndex): 查找数组项,返回对应的下标
  • reduce / reduceRight(fn(prev, cur), defaultPrev): 两两执行,prev 为上次化简函数的 return 值,cur 为当前值(从第二项开始)

数组乱序:

1
2
3
4
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
arr.sort(function () {
return Math.random() - 0.5;
});

数组拆解:

1
2
3
4
5
6
7
// flat: [1,[2,3]] --> [1, 2, 3]

Array.prototype.flat = function () {
return this.toString()
.split(",")
.map((item) => +item);
};

类数组和数组的区别是什么?
类数组:
1)拥有 length 属性,其它属性(索引)为非负整数(对象中的索引会被当做字符串来处理);
2)不具有数组所具有的方法;
类数组是一个普通对象,而真实的数组是 Array 类型。
常见的类数组有: 函数的参数 arugments, DOM 对象列表 (比如通过 document.querySelectorAll 得到的列表), jQuery 对象 (比如 $(“div”))。

类数组可以转换为数组:

1
2
3
4
5
6
// 第一种方法
Array.prototype.slice.call(arrayLike, start);
// 第二种方法
[...arrayLike];
// 第三种方法:
Array.from(arrayLike);

PS: 任何定义了遍历器(Iterator)接口的对象,都可以用扩展运算符转为真正的数组。

Array.from 方法用于将两类对象转为真正的数组:类似数组的对象(array-like object)和可遍历(iterable)的对象。