数组

判空 #

if (!array || array.length <= 0) { 
	console.error("array is null");
}
if (!Array.isArray(array) || array.length == 0) {
  console.error("array is null");
}

数组循环前无需检查长度为空,除非使用 do…while

<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice">splice</a> #

splice(start)
splice(start, deleteCount)
splice(start, deleteCount, item1)
splice(start, deleteCount, item1, item2)
splice(start, deleteCount, item1, item2, /* …, */ itemN)

start

从 0 开始计算的索引,表示要开始改变数组的位置,它会被转换成整数

  • 负索引从数组末尾开始计算——如果 -array.length <= start < 0,使用 start + array.length
  • 如果 start < -array.length,使用 0
  • 如果 start >= array.length,则不会删除任何元素,但是该方法会表现为添加元素的函数,添加所提供的那些元素。
  • 如果 start 被省略了(即调用 splice() 时不传递参数),则不会删除任何元素。这与传递 undefined 不同,后者会被转换为 0

返回被删除元素的数组。

find #

find() 查找数组中第一个满足条件的元素,没有满足条件的元素则返回 undefinedfind() 方法会跳过 nullundefined 元素,但会对其他假值(如 0, NaN, '' 等)进行测试。

filter #

filter() 过滤数组中所有满足条件的元素。

// 第一个参数 { length: 5 } 将创建一个有 5 个元素的数组,值都是 undefined,也即 v 是 undefined。
// i 是序号,从 0 开始,通过箭头函数隐式返回 i,因此最终数组是 [0, 1, 2, 3, 4]。
Array.from({ length: 5 }, (v, i) => i)

delete #

delete 删除数组中的元素。

> var a = [1, 2, 3];
> delete a[1];
true
> a;
[1, undefined, 3] 
> typeof a[1]; 
"undefined"

TypeScript 之数组