Array
数组是一种类列表对象,它的原型中提供了遍历和修改元素的相关操作。JavaScript 数组的长度和元素类型都是非固定的。因为数组的长度可随时改变,并且其数据在内存中也可以不连续,所以 JavaScript 数组不一定是密集型的,这取决于它的使用方式。
创建数组
``` let fruits = ['Apple', 'Banana']
console.log(fruits.length) // 2 ```
Copy to Clipboard
通过索引访问数组元素
``` let first = fruits[0] // Apple
let last = fruits[fruits.length - 1] // Banana ```
Copy to Clipboard
常用方法
Array.pop()
从数组中删除最后一个元素,并返回该元素的值。此方法会更改数组的长度
``` const myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
const popped = myFish.pop();
console.log(myFish); // ['angel', 'clown', 'mandarin']
console.log(popped); // 'sturgeon' ```
Array.push()
将一个或多个元素添加到数组的末尾,并返回该数组的新长度。
``` var sports = ["soccer", "baseball"]; var total = sports.push("football", "swimming");
console.log(sports); // ["soccer", "baseball", "football", "swimming"]
console.log(total); // 4 ```
Array.reduce()
对数组中的每个元素按序执行一个由您提供的 reducer 函数,每一次运行 reducer 会将先前元素的计算结果作为参数传入,最后将其结果汇总为单个返回值。
``` const array1 = [1, 2, 3, 4];
// 0 + 1 + 2 + 3 + 4 const initialValue = 0; const sumWithInitial = array1.reduce( (previousValue, currentValue) => previousValue + currentValue, initialValue );
console.log(sumWithInitial); // expected output: 10
```
Array.reduceRight()
接受一个函数作为累加器(accumulator)和数组的每个值(从右到左)将其减少为单个值。
``` const array1 = [[0, 1], [2, 3], [4, 5]];
const result = array1.reduceRight((accumulator, currentValue) => accumulator.concat(currentValue));
console.log(result); // expected output: Array [4, 5, 2, 3, 0, 1] ```
Array.reverse()
将数组中元素的位置颠倒,并返回该数组。数组的第一个元素会变成最后一个,数组的最后一个元素变成第一个。该方法会改变原数组。
``` const array1 = ['one', 'two', 'three']; console.log('array1:', array1); // expected output: "array1:" Array ["one", "two", "three"]
const reversed = array1.reverse(); console.log('reversed:', reversed); // expected output: "reversed:" Array ["three", "two", "one"]
// Careful: reverse is destructive -- it changes the original array. console.log('array1:', array1); // expected output: "array1:" Array ["three", "two", "one"]
```
Array.shift()
从数组中删除第一个元素,并返回该元素的值。此方法更改数组的长度。 ``` const array1 = [1, 2, 3];
const firstElement = array1.shift();
console.log(array1); // expected output: Array [2, 3]
console.log(firstElement); // expected output: 1 ```
Array.slice()
返回一个新的数组对象,这一对象是一个由
begin
和end
决定的原数组的浅拷贝(包括begin
,不包括end
)。原始数组不会被改变。
``` 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"] ```
总结一下
今天就先这么多吧,主要介绍了JS数组Array常用方法汇总和实例,JavaScript中的Array的方法比较多,大家按需参考,希望可以给你带来帮助。