# Array

Array 对象是用于构造数组的全局对象,数组是类似于列表的高阶对象。

# 实例属性

# length

length 是 Array 的实例属性,表示该数组中元素的个数。该值是一个无符号 32 位整数,并且其数值总是大于数组最大索引。

const clothing = ['shoes', 'shirts', 'socks', 'sweaters'];
console.log(clothing.length);
// expected output: 4

兼容性

Android uni-app x iOS uni-app x web uni-app x Android uni-app iOS uni-app web uni-app
3.9 4.11 4.0

边界情况说明:

  • 在不同平台上,数组的长度限制不同,超出限制会导致相应的错误或异常
    • 编译至 JavaScript 平台时,最大长度为 2^32 - 1,超出限制会报错:Invalid array length
    • 编译至 Kotlin 平台时,最大长度受系统内存的限制,超出限制报错:java.lang.OutOfMemoryError: Failed to allocate a allocation until OOM
    • 编译至 Swift 平台时,最大长度也受系统内存的限制,目前超出限制没有返回信息。

# 实例方法

# find(predicate, thisArg?)

find() 方法返回数组中满足提供的测试函数的第一个元素的值。否则返回 null。

参数

名称 类型 必填 描述
predicate (value : T, index : number, obj : T[]) => value is S 为数组中的每个元素执行的函数。它应该返回一个真值来表示已经找到了匹配的元素。
thisArg any 执行 callbackFn 时用作 this 的值。

返回值

类型 描述
S | null 数组中第一个满足所提供测试函数的元素的值,否则返回 null
const array1 = [5, 12, 8, 130, 44];

const found = array1.find((element:number):boolean => element > 10);

console.log(found);
// expected output: 12

兼容性

Android uni-app x iOS uni-app x web uni-app x Android uni-app iOS uni-app web uni-app
3.9 4.11 4.0

# findIndex(predicate, thisArg?)

findIndex() 方法返回数组中满足提供的测试函数的第一个元素的索引。若没有找到对应元素则返回 -1。

参数

名称 类型 必填 描述
predicate (value : T, index : number, obj : T[]) => unknown 为数组中的每个元素执行的函数。它应该返回一个真值以指示已找到匹配元素,否则返回一个假值。
thisArg any 执行 callbackFn 时用作 this 的值。

返回值

类型 描述
number 数组中第一个满足测试条件的元素的索引。否则返回 -1。
const array1 = [5, 12, 8, 130, 44];

const isLargeNumber = (element:number):boolean => element > 13;

console.log(array1.findIndex(isLargeNumber));
// expected output: 3

兼容性

Android uni-app x iOS uni-app x web uni-app x Android uni-app iOS uni-app web uni-app
3.9 4.11 4.0

# fill(value, start?, end?)

fill() 方法用一个固定值填充一个数组中从起始索引(默认为 0)到终止索引(默认为 array.length)内的全部元素。它返回修改后的数组。

参数

名称 类型 必填 描述
value T 用来填充数组元素的值。注意所有数组中的元素都将是这个确定的值:如果 value 是个对象,那么数组的每一项都会引用这个元素。
start number 基于零的索引,从此开始填充,转换为整数。
end number 基于零的索引,在此结束填充,转换为整数。fill() 填充到但不包含 end 索引。

返回值

类型
this
const array1 = [1, 2, 3, 4];

// fill with 0 from position 2 until position 4
console.log(array1.fill(0, 2, 4));
// expected output: [1, 2, 0, 0]

// fill with 5 from position 1
console.log(array1.fill(5, 1));
// expected output: [1, 5, 5, 5]

console.log(array1.fill(6));
// expected output: [6, 6, 6, 6]

兼容性

Android uni-app x iOS uni-app x web uni-app x Android uni-app iOS uni-app web uni-app
3.9 4.11 4.0

# copyWithin(target, start?, end?)

copyWithin() 方法浅复制数组的一部分到同一数组中的另一个位置,并返回它,不会改变原数组的长度。

参数

名称 类型 必填 描述
target number 序列开始替换的目标位置,以 0 为起始的下标表示,且将被转换为整数
start number 要复制的元素序列的起始位置,以 0 为起始的下标表示,且将被转换为整数
end number 要复制的元素序列的结束位置,以 0 为起始的下标表示,且将被转换为整数。copyWithin 将会拷贝到该位置,但不包括 end 这个位置的元素。

返回值

类型
this
const array1 = ['a', 'b', 'c', 'd', 'e'];
// copy to index 0 the element at index 3
console.log(array1.copyWithin(0, 3, 4));
// expected output: Array ["d", "b", "c", "d", "e"]
// copy to index 1 all elements from index 3 to the end
console.log(array1.copyWithin(1, 3));
// expected output: Array ["d", "d", "e", "d", "e"]

兼容性

Android uni-app x iOS uni-app x web uni-app x Android uni-app iOS uni-app web uni-app
3.9 4.11 4.0

# pop()

pop() 方法从数组中删除最后一个元素,并返回该元素的值。此方法会更改数组的长度。

返回值

类型
T | null
const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];

console.log(plants.pop());
// expected output: "tomato"

console.log(plants);
// expected output: Array ["broccoli", "cauliflower", "cabbage", "kale"]

plants.pop();

console.log(plants);
// expected output: Array ["broccoli", "cauliflower", "cabbage"]

兼容性

Android uni-app x iOS uni-app x web uni-app x Android uni-app iOS uni-app web uni-app
3.9 4.11 4.0

# push(...items)

push() 方法将指定的元素添加到数组的末尾,并返回新的数组长度。

参数

名称 类型 必填 描述
items T[] 添加到数组末尾的元素。

返回值

类型 描述
number 调用方法的对象的新 length 属性。
const animals = ['pigs', 'goats', 'sheep'];

const count = animals.push('cows');
console.log(count);
// expected output: 4
console.log(animals);
// expected output: Array ["pigs", "goats", "sheep", "cows"]

animals.push('chickens', 'cats', 'dogs');
console.log(animals);
// expected output: Array ["pigs", "goats", "sheep", "cows", "chickens", "cats", "dogs"]

兼容性

Android uni-app x iOS uni-app x web uni-app x Android uni-app iOS uni-app web uni-app
3.9 4.11 4.0

# concat(...items)

concat() 方法用于合并两个或多个数组。此方法不会更改现有数组,而是返回一个新数组。

参数

名称 类型 必填 描述
items ConcatArray<T>[] 数组和/或值,将被合并到一个新的数组中。如果省略了所有 valueN 参数,则 concat 会返回调用此方法的现存数组的一个浅拷贝。详情请参阅下文描述。

返回值

类型 描述
T[] 新的 Array 实例。
const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);
console.log(array3);
// expected output: Array ["a", "b", "c", "d", "e", "f"]

兼容性

Android uni-app x iOS uni-app x web uni-app x Android uni-app iOS uni-app web uni-app
3.9 4.11 4.0

# concat(...items)

concat() 方法用于合并两个或多个数组。此方法不会更改现有数组,而是返回一个新数组。

参数

名称 类型 必填 描述
items (T | ConcatArray<T>)[] 数组和/或值,将被合并到一个新的数组中。如果省略了所有 valueN 参数,则 concat 会返回调用此方法的现存数组的一个浅拷贝。详情请参阅下文描述。

返回值

类型 描述
T[] 新的 Array 实例。

兼容性

Android uni-app x iOS uni-app x web uni-app x Android uni-app iOS uni-app web uni-app
3.9 4.11 4.0

# join(separator?)

join() 方法将一个数组(或一个类数组对象)的所有元素连接成一个字符串并返回这个字符串,用逗号或指定的分隔符字符串分隔。如果数组只有一个元素,那么将返回该元素而不使用分隔符。

参数

名称 类型 必填 描述
separator string 指定一个字符串来分隔数组的每个元素。如果需要,将分隔符转换为字符串。如果省略,数组元素用逗号(,)分隔。如果 separator 是空字符串(""),则所有元素之间都没有任何字符。

返回值

类型 描述
string 一个所有数组元素连接的字符串。如果 arr.length 为 0,则返回空字符串。
const elements = ['Fire', 'Air', 'Water'];

console.log(elements.join());
// expected output: "Fire,Air,Water"

console.log(elements.join(''));
// expected output: "FireAirWater"

console.log(elements.join('-'));
// expected output: "Fire-Air-Water"

兼容性

Android uni-app x iOS uni-app x web uni-app x Android uni-app iOS uni-app web uni-app
3.9 4.11 - -

# reverse()

reverse() 方法就地反转数组中的元素,并返回同一数组的引用。数组的第一个元素会变成最后一个,数组的最后一个元素变成第一个。换句话说,数组中的元素顺序将被翻转,变为与之前相反的方向。

返回值

类型 描述
T[] 原始数组反转后的引用。注意,数组是就地反转的,并且没有复制。

兼容性

Android uni-app x iOS uni-app x web uni-app x Android uni-app iOS uni-app web uni-app
3.9 4.11 4.0

# shift()

shift() 方法从数组中删除第一个元素,并返回该元素的值。此方法更改数组的长度。

返回值

类型 描述
T | null 从数组中删除的元素;如果数组为空则返回 null。
const array1 = [1, 2, 3];

const firstElement = array1.shift();

console.log(array1);
// expected output: Array [2, 3]

console.log(firstElement);
// expected output: 1

兼容性

Android uni-app x iOS uni-app x web uni-app x Android uni-app iOS uni-app web uni-app
3.9 4.11 4.0

# slice(start?, end?)

slice() 方法返回一个新的数组对象,这一对象是一个由 start 和 end 决定的原数组的浅拷贝(包括 start,不包括 end),其中 start 和 end 代表了数组元素的索引。原始数组不会被改变。

参数

名称 类型 必填 描述
start number 提取起始处的索引(从 0 开始),会转换为整数。
end number 提取终止处的索引(从 0 开始),会转换为整数。slice() 会提取到但不包括 end 的位置。

返回值

类型
T[]
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]

console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]

console.log(animals.slice(1, 5));
// expected output: Array ["bison", "camel", "duck", "elephant"]

console.log(animals.slice(-2));
// expected output: Array ["duck", "elephant"]

console.log(animals.slice(2, -1));
// expected output: Array ["camel", "duck"]

console.log(animals.slice());
// expected output: Array ["ant", "bison", "camel", "duck", "elephant"]

兼容性

Android uni-app x iOS uni-app x web uni-app x Android uni-app iOS uni-app web uni-app
3.9 4.11 4.0

# sort(compareFn?)

sort() 方法就地对数组的元素进行排序,并返回对相同数组的引用。默认排序是将元素转换为字符串,然后按照它们的 UTF-16 码元值升序排序。

参数

名称 类型 必填 描述
compareFn (a : T, b : T) => number 定义排序顺序的函数。返回值应该是一个数字,其正负性表示两个元素的相对顺序。该函数使用以下参数调用: a:第一个用于比较的元素。不会是 null。 b:第二个用于比较的元素。不会是 null。 如果省略该函数,数组元素会被转换为字符串,然后根据每个字符的 Unicode 码位值进行排序。

返回值

类型 描述
this 经过排序的原始数组的引用。注意数组是就地排序的,不会进行复制。
const array2 = [5, 1, 4, 2, 3];
array2.sort((a: number, b: number):number => a - b);
// expect(array2).toEqual([1, 2, 3, 4, 5]);

兼容性

Android uni-app x iOS uni-app x web uni-app x Android uni-app iOS uni-app web uni-app
3.9 4.11 4.0

平台差异性

在android平台,一定不能忽略两个对比元素相等的场景,否则可能会出现java.lang.IllegalArgumentException: Comparison method violates its general contract!‌


a.sort((a, b) : number => {
  // 这里的判断不能省略
  if(a.compareTo(b) == 0){
    return 0
  }
  return a - b
})

# splice(start, deleteCount, ...items)

splice() 方法通过移除或者替换已存在的元素和/或添加新元素就地改变一个数组的内容。

参数

名称 类型 必填 描述
start number 从 0 开始计算的索引,表示要开始改变数组的位置,它会被转换成整数。
deleteCount number 一个整数,表示数组中要从 start 开始删除的元素数量。

返回值

类型 描述
T[] 一个包含了删除的元素的数组。
const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// inserts at index 1
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "June"]

months.splice(4, 1, 'May');
// replaces 1 element at index 4
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "May"]

兼容性

Android uni-app x iOS uni-app x web uni-app x Android uni-app iOS uni-app web uni-app
x x 4.0 x x

# unshift(...items)

unshift() 方法将指定元素添加到数组的开头,并返回数组的新长度。

参数

名称 类型 必填 描述
items T[] 添加到 arr 开头的元素。

返回值

类型
number
const array1 = [1, 2, 3];

console.log(array1.unshift(4, 5));
// expected output: 5

console.log(array1);
// expected output: Array [4, 5, 1, 2, 3]

兼容性

Android uni-app x iOS uni-app x web uni-app x Android uni-app iOS uni-app web uni-app
3.9 4.11 4.0

# indexOf(searchElement, fromIndex?)

indexOf() 方法返回数组中第一次出现给定元素的下标,如果不存在则返回 -1。

参数

名称 类型 必填 描述
searchElement T 数组中要查找的元素。
fromIndex number 开始搜索的索引(从零开始),会转换为整数。

返回值

类型
number
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];

console.log(beasts.indexOf('bison'));
// expected output: 1

// start from index 2
console.log(beasts.indexOf('bison', 2));
// expected output: 4

console.log(beasts.indexOf('giraffe'));
// expected output: -1

兼容性

Android uni-app x iOS uni-app x web uni-app x Android uni-app iOS uni-app web uni-app
3.9 4.11 4.0

# lastIndexOf(searchElement, fromIndex?)

lastIndexOf() 方法返回数组中给定元素最后一次出现的索引,如果不存在则返回 -1。该方法从 fromIndex 开始向前搜索数组。

参数

名称 类型 必填 描述
searchElement T 被查找的元素。
fromIndex number 以 0 起始的索引,表明反向搜索的起始位置,会被转换为整数。

返回值

类型
number
const animals = ['Dodo', 'Tiger', 'Penguin', 'Dodo'];

console.log(animals.lastIndexOf('Dodo'));
// expected output: 3

console.log(animals.lastIndexOf('Tiger'));
// expected output: 1

兼容性

Android uni-app x iOS uni-app x web uni-app x Android uni-app iOS uni-app web uni-app
3.9 4.11 4.0

# every(predicate, thisArg?)

every() 方法测试一个数组内的所有元素是否都能通过指定函数的测试。它返回一个布尔值。

参数

名称 类型 必填 描述
predicate (value : T, index ?: number, array ?: T[]) => value is S 为数组中的每个元素执行的函数。它应该返回一个真值以指示元素通过测试,否则返回一个假值。该函数被调用时将传入以下参数: value:数组中当前正在处理的元素。 index:正在处理的元素在数组中的索引。 array:调用了 every() 的数组本身。
thisArg any 执行 callbackFn 时用作 this 的值

返回值

类型
this is S[]
const isBelowThreshold = (currentValue:number):boolean => currentValue < 40;
const array1 = [1, 30, 39, 29, 10, 13];
console.log(array1.every(isBelowThreshold));
// expected output: true

兼容性

Android uni-app x iOS uni-app x web uni-app x Android uni-app iOS uni-app web uni-app
x x 4.0 x x

# some(predicate, thisArg?)

some() 方法测试数组中是否至少有一个元素通过了由提供的函数实现的测试。如果在数组中找到一个元素使得提供的函数返回 true,则返回 true;否则返回 false。它不会修改数组。

参数

名称 类型 必填 描述
predicate (value : T, index : number, array : T[]) => unknown 为数组中的每个元素执行的函数。它应该返回一个真值以指示元素通过测试,否则返回一个假值。该函数被调用时将传入以下参数: value:数组中当前正在处理的元素。 index:正在处理的元素在数组中的索引。 array:调用了 some() 的数组本身。
thisArg any 执行 callbackFn 时用作 this 的值。

返回值

类型 描述
boolean 如果回调函数对数组中至少一个元素返回一个真值,则返回 true。否则返回 false。
const array = [1, 2, 3, 4, 5];

// checks whether an element is even
const even = (element:number):boolean=> element % 2 == 0;

console.log(array.some(even));
// expected output: true

兼容性

Android uni-app x iOS uni-app x web uni-app x Android uni-app iOS uni-app web uni-app
3.9 4.11 4.0

# forEach(callbackfn, thisArg?)

forEach() 方法对数组的每个元素执行一次给定的函数。

参数

名称 类型 必填 描述
callbackfn (value : T, index : number, array : T[]) => void 为数组中每个元素执行的函数。并会丢弃它的返回值。该函数被调用时将传入以下参数: value:数组中正在处理的当前元素。 index:数组中正在处理的当前元素的索引。 array:调用了 forEach() 的数组本身。
thisArg any 执行 callbackFn 时用作 this 的值。

返回值

类型
void
const array1 = ['a', 'b', 'c'];
array1.forEach(element => console.log(element));
// expected output: "a"
// expected output: "b"
// expected output: "c"

特别注意: 不可在 forEach 的 callbackFn 里添加或者删除原数组元素,此行为是危险的,在 Android 平台会造成闪退,在 iOS 平台会造成行为不符合预期。如果想实现该效果,请用 while 循环。


const array1 = ['a', 'b', 'c'];
array1.forEach(element => {
	console.log(element)
	array1.pop() // 此行为在 Android 平台会造成闪退,在 iOS 平台会输出 'a', 'b', 'c', 而 JS 会输出 'a', 'b'
});

// 如果想让上述行为正常运行,可以用 while 循环实现:

let array1 = ['a', 'b', 'c'];
let index = 0;
while (index < array1.length) {
  console.log(array1[index]);
  array1.pop();
  index += 1;
}

兼容性

Android uni-app x iOS uni-app x web uni-app x Android uni-app iOS uni-app web uni-app
3.9 4.11 4.0

# map(callbackfn, thisArg?)

map() 方法创建一个新数组,这个新数组由原数组中的每个元素都调用一次提供的函数后的返回值组成。

参数

名称 类型 必填 描述
callbackfn (value : T, index : number, array : T[]) => U 为数组中的每个元素执行的函数。它的返回值作为一个元素被添加为新数组中。该函数被调用时将传入以下参数: value:数组中当前正在处理的元素。 index:正在处理的元素在数组中的索引。 array:调用了 map() 的数组本身。
thisArg any 执行 callbackFn 时用作 this 的值

返回值

类型
U[]
const array1 = [1, 4, 9, 16];

// pass a function to map
const map1 = array1.map((x:number):number => x * 2);

console.log(map1);
// expected output: Array [2, 8, 18, 32]

兼容性

Android uni-app x iOS uni-app x web uni-app x Android uni-app iOS uni-app web uni-app
3.9 4.11 4.0

# filter(predicate, thisArg?)

filter() 方法创建给定数组一部分的浅拷贝,其包含通过所提供函数实现的测试的所有元素。

参数

名称 类型 必填 描述
predicate (value : T, index ?: number, array ?: T[]) => value is S 为数组中的每个元素执行的函数。它应该返回一个真值以将元素保留在结果数组中,否则返回一个假值。该函数被调用时将传入以下参数: value:数组中当前正在处理的元素。 index:正在处理的元素在数组中的索引。 array:调用了 filter() 的数组本身。
thisArg any 执行 callbackFn 时用作 this 的值

返回值

类型
S[]
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter((word:string):boolean => word.length > 6);

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]

兼容性

Android uni-app x iOS uni-app x web uni-app x Android uni-app iOS uni-app web uni-app
x x 4.0 x x

# reduce(callbackfn)

reduce() 方法对数组中的每个元素按序执行一个提供的 reducer 函数,每一次运行 reducer 会将先前元素的计算结果作为参数传入,最后将其结果汇总为单个返回值。

参数

名称 类型 必填 描述
callbackfn (previousValue : T, currentValue : T, currentIndex : number, array : T[]) => T 为数组中每个元素执行的函数。其返回值将作为下一次调用 callbackFn 时的 accumulator 参数。对于最后一次调用,返回值将作为 reduce() 的返回值。该函数被调用时将传入以下参数: previousValue:上一次调用 callbackFn 的结果。在第一次调用时,如果指定了 initialValue 则为指定的值,否则为 array[0] 的值。 currentValue:当前元素的值。在第一次调用时,如果指定了 initialValue,则为 array[0] 的值,否则为 array[1]。 currentIndex:currentValue 在数组中的索引位置。在第一次调用时,如果指定了 initialValue 则为 0,否则为 1 array:调用了 reduce() 的数组本身。

返回值

类型
T
const array1 = [1, 2, 3, 4];

// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
  (previousValue:number, currentValue:number):number => previousValue + currentValue,
  initialValue
);

console.log(sumWithInitial);
// expected output: 10

兼容性

Android uni-app x iOS uni-app x web uni-app x Android uni-app iOS uni-app web uni-app
3.9 4.11 4.0

# reduceRight(callbackfn)

reduceRight() 方法对累加器(accumulator)和数组的每个值(按从右到左的顺序)应用一个函数,并使其成为单个值。

参数

名称 类型 必填 描述
callbackfn (previousValue : T, currentValue : T, currentIndex : number, array : T[]) => T 为数组中的每个元素执行的函数。其返回值将作为下一次调用 callbackFn 时的 accumulator 参数。对于最后一次调用,返回值将成为 reduceRight() 的返回值。该函数被调用时将传入以下参数: previousValue:上一次调用 callbackFn 的结果。在第一次调用时,如果指定了 initialValue 则为指定的值,否则为数组最后一个元素的值。 currentValue:数组中当前正在处理的元素。 currentIndex:正在处理的元素在数组中的索引。 array:调用了 reduceRight() 的数组本身。

返回值

类型
T

兼容性

Android uni-app x iOS uni-app x web uni-app x Android uni-app iOS uni-app web uni-app
3.9 4.11 4.0

# isArray(arg)

Array.isArray() 静态方法用于确定传递的值是否是一个 Array。

参数

名称 类型 必填 描述
arg any 需要检测的值。

返回值

类型 描述
arg is any[] 如果 value 是 Array,则为 true;否则为 false。如果 value 是 TypedArray 实例,则总是返回 false。
console.log(Array.isArray([1, 3, 5]));
// Expected output: true

console.log(Array.isArray('[]'));
// Expected output: false

console.log(Array.isArray(new Array(5)));
// Expected output: true

console.log(Array.isArray(new Int16Array([15, 33])));
// Expected output: false

兼容性

Android uni-app x iOS uni-app x web uni-app x Android uni-app iOS uni-app web uni-app
3.9 4.11 4.0

# includes(searchElement, fromIndex?)

includes() 方法用来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true,否则返回 false。

参数

名称 类型 必填 描述
searchElement any 需要查找的值。
fromIndex number 可选。开始搜索的索引(从零开始),会转换为整数。

返回值

类型 描述
boolean 一个布尔值,如果在数组中(或者在 fromIndex 所指示的数组部分中,如果指定 fromIndex 的话)找到 searchElement 值,则该值为 true。

兼容性

Android uni-app x iOS uni-app x web uni-app x Android uni-app iOS uni-app web uni-app
3.9 4.11 4.0

# toKotlinList()

toKotlinList() 将当前的Array对象转换为 kotlin 中对应的List对象

返回值

类型
kotlin.collections.List<any>

兼容性

Android uni-app x iOS uni-app x web uni-app x Android uni-app iOS uni-app web uni-app
3.9 x - 3.9+ x -

# 参见

相关 Bug

# Android 平台方法

  • 目前 Array 类型编译到 kotlinio.dcloud.uts.UTSArray, 该类继承自 java.util.ArrayList,所有java /kotlin 为其提供的扩展函数(如:toTypedArray 等),均可以正常调用。

# 常见操作

  • 创建数组
const fruits = ['Apple', 'Banana']
console.log(fruits.length)
  • 通过索引访问数组元素
const first = fruits[0]
// Apple
const last = fruits[fruits.length - 1]
// Banana
  • 遍历数组
fruits.forEach(function(item, index, array) {
  console.log(item, index)
})
// Apple 0
// Banana 1
  • 注意:数组遍历不推荐使用 for in 语句,因为在 ts 中 for in 遍历的是数组的下标,而在 Swift 和 Kottlin 中遍历的是数组的元素,存在行为不一致。

  • 添加元素到数组的末尾

const newLength = fruits.push('Orange')
// ["Apple", "Banana", "Orange"]
  • 删除数组末尾的元素
const last = fruits.pop() // remove Orange (from the end)
// ["Apple", "Banana"]
  • 删除数组头部元素
const first = fruits.shift() // remove Apple from the front
// ["Banana"]
  • 添加元素到数组的头部
const newLength = fruits.unshift('Strawberry') // add to the front
// ["Strawberry", "Banana"]
  • 找出某个元素在数组中的索引
fruits.push('Mango')
// ["Strawberry", "Banana", "Mango"]
const pos = fruits.indexOf('Banana')
// 1
  • 通过索引删除某个元素
const removedItem = fruits.splice(pos, 1) // this is how to remove an item
// ["Strawberry", "Mango"]
  • 从一个索引位置删除多个元素
const vegetables = ['Cabbage', 'Turnip', 'Radish', 'Carrot']
console.log(vegetables)
// ["Cabbage", "Turnip", "Radish", "Carrot"]
const pos = 1
const n = 2
const removedItems = vegetables.splice(pos, n)
// this is how to remove items, n defines the number of items to be removed,
// starting at the index position specified by pos and progressing toward the end of array.
console.log(vegetables)
// ["Cabbage", "Carrot"] (the original array is changed)
console.log(removedItems)
// ["Turnip", "Radish"]
  • 复制一个数组
const shallowCopy = fruits.slice() // this is how to make a copy
// ["Strawberry", "Mango"]

# 访问数组元素

数组的索引是从 0 开始的,第一个元素的索引为 0,最后一个元素的索引等于该数组的 长度 减 1。

如果指定的索引是一个无效值,将会抛出 IndexOutOfBoundsException 异常

下面的写法是错误的,运行时会抛出 SyntaxError 异常,而原因则是使用了非法的属性名:

console.log(arr.0) // a syntax error