ZetCode

JavaScript 数组

最后修改于 2023 年 10 月 18 日

在本文中,我们将展示如何在 JavaScript 中使用数组。

数组是多个值的集合。数组项称为数组的元素。每个元素都可以通过索引来引用。数组是基于零的。

JavaScript 数组初始化

在第一个示例中,我们将展示如何在 JavaScript 中初始化数组。

array_init.js
"use strict";

const nums = [1, 2, 3, 4, 5];

console.log(nums);

该示例在 JavaScript 中创建一个简单的数组。

const nums = [1, 2, 3, 4, 5];

使用方括号创建数组。元素由逗号分隔。

$ nodejs array_init.js
[ 1, 2, 3, 4, 5 ]

JavaScript 数组索引

下一个示例展示了 JavaScript 中的数组索引操作。

array_index.js
"use strict";

const nums = [1, 2, 3, 4, 5, 1];

const e1 = nums[0];
console.log(e1);

nums[2] = 22;
console.log(nums[2]);

console.log(nums.indexOf(1));
console.log(nums.lastIndexOf(1));

我们使用索引操作来获取和修改数组值,并获取元素的索引。

const e1 = nums[0];

我们获取数组的第一个元素。索引从零开始。

nums[2] = 22;

我们修改数组的第三个值。

console.log(nums.indexOf(1));

使用 indexOf,我们获取元素 1 的第一次出现。

console.log(nums.lastIndexOf(1));

使用 lastIndexOf,我们获取元素 1 的最后一次出现。

$ nodejs array_index.js
1
22
0
5

JavaScript 数组基本操作

以下示例展示了 JavaScript 数组的一些基本操作。

basic_oper.js
"use strict";

const words = [];
words.push("pen");
words.push("pencil", "knife", "chair");

console.log(words);

const el1 = words.shift();
console.log(el1);
console.log(words);

const el2 = words.pop();
console.log(el2);
console.log(words);

在示例中,我们展示了 JavaScript 数组的 pushshiftpop 方法。

const words = [];
words.push("pen");
words.push("pencil", "knife", "chair");

创建一个空数组。使用 push 方法,我们在数组的末尾添加一个或多个元素。

const el1 = words.shift();

shift 方法从数组中删除第一个元素并返回已删除的元素。它会更改数组的长度。

const el2 = words.pop();

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

$ nodejs basic_oper.js
[ 'pen', 'pencil', 'knife', 'chair' ]
pen
[ 'pencil', 'knife', 'chair' ]
chair
[ 'pencil', 'knife' ]

JavaScript 循环数组

在下一个示例中,我们遍历 JavaScript 数组。

array_loop.js
"use strict";

const words = ["pen", "pencil", "rock", "sky", "earth"];

words.forEach(e => console.log(e));

for (let word of words) {

    console.log(word);
}

for (let idx in words) {

    console.log(words[idx]);
}

const len = words.length;

for (let i = 0; i < len; i++) {

    console.log(words[i]);
}

const i = 0;

while (i < len) {

    console.log(words[i]);
    i++;
}

该示例展示了循环遍历 JavaScript 数组的四种方法。

words.forEach(e => console.log(e));

我们使用 forEach 方法来遍历数组。它为每个数组元素执行提供的函数一次。

for (let word of words) {

    console.log(word);
}

使用 for of 循环,我们遍历数组的值。

for (let idx in words) {

    console.log(words[idx]);
}

使用 for in 循环,我们遍历数组的索引。

var len = words.length;

for (let i = 0; i < len; i++) {

    console.log(words[i]);
}

在这里,我们使用类似 C 的 for 循环来遍历数组。

var i = 0;

while (i < len) {

    console.log(words[i]);
    i++;
}

最后,我们使用 while 循环来遍历数组。

JavaScript 数组切片

slice 方法返回数组一部分的浅拷贝。该方法接受一个或两个参数,用于指定选择的索引。原始数组不会被修改。

array_slice.js
"use strict";

const nums = [2, -3, 4, 6, -1, 9, -7];

const res = nums.slice(3);
console.log(res);

const res2 = nums.slice(2, 4);
console.log(res2);

在示例中,我们创建了两个切片。

const res = nums.slice(3);

我们从索引 3 开始到数组的末尾创建一个切片。

const res2 = nums.slice(2, 4);

我们从索引 2 到索引 4 创建一个切片;结束索引不包含在内。

$ nodejs array_slice.js
[ 6, -1, 9, -7 ]
[ 4, 6 ]

在 JavaScript 中对数组进行排序

sort 方法对数组的元素进行原地排序并返回数组。默认排序顺序是根据字符串 Unicode 码位。sort 方法接受一个可选的函数,该函数定义排序顺序。

array_sort.js
"use strict";

const nums = [2, 3, 1, 6, 5, 8, 9, 0];

nums.sort();
console.log(nums);

nums.reverse();
console.log(nums);

const persons = [
    {name: 'Peter', age: 21},
    {name: 'Robert', age: 37},
    {name: 'Martin', age: 45},
    {name: 'Jane', age: 31}
];

persons.sort((a, b) => a.age - b.age);
console.log(persons);

persons.sort((a, b) => {

    const nameA = a.name.toLowerCase(), nameB = b.name.toLowerCase();

    if (nameA < nameB) {
        return -1;
    } else if (nameA > nameB) {
        return 1;
    } else {
        return 0;
    }
});

console.log(persons);

该示例对整数数组和对象数组进行排序。

nums.sort();

sort 方法按升序对整数数组进行排序。

nums.reverse();

reverse 方法按降序对整数数组进行排序。

persons.sort((a, b) => a.age - b.age);

我们按年龄属性对人员对象数组进行排序。

persons.sort((a, b) => {

    const nameA = a.name.toLowerCase(), nameB = b.name.toLowerCase();

    if (nameA < nameB) {
        return -1;
    } else if (nameA > nameB) {
        return 1;
    } else {
        return 0;
    }
});

我们按姓名属性对人员对象数组进行排序。

$ nodejs array_sort.js
[ 0, 1, 2, 3, 5, 6, 8, 9 ]
[ 9, 8, 6, 5, 3, 2, 1, 0 ]
[ { name: 'Peter', age: 21 },
  { name: 'Jane', age: 31 },
  { name: 'Robert', age: 37 },
  { name: 'Martin', age: 45 } ]
[ { name: 'Jane', age: 31 },
  { name: 'Martin', age: 45 },
  { name: 'Peter', age: 21 },
  { name: 'Robert', age: 37 } ]

JavaScript 多维数组

在 JavaScript 中,我们可以创建多维数组。

multi_dim.js
"use strict";

const nums = [2, 3, 2, [33, 44, 55], [7, 8, [77, 88]]];

console.log(nums[2]);

console.log(nums[3]);
console.log(nums[3][0]);

console.log(nums[4][0]);
console.log(nums[4][2][0]);

通过将数组嵌套到其他数组中来创建多维数组。

const nums = [2, 3, 2, [33, 44, 55], [7, 8, [77, 88]]];

我们定义了一个多维数组。

console.log(nums[2]);

要从第一维获取元素,我们使用一对方括号。

console.log(nums[3]);

这行代码打印整个内部数组。

console.log(nums[3][0]);

要从内部数组获取元素,我们使用两对方括号。

console.log(nums[4][2][0]);

这里我们从第三维获取一个值。

$ nodejs multi_dim.js
2
[ 33, 44, 55 ]
33
7
77

JavaScript 过滤数组

filter 方法创建一个新数组,其中包含通过给定函数实现的测试的所有元素。

filter_array.js
"use strict"

const nums = [2, -3, 4, 6, -1, 9, -7];

const res = nums.filter(e => e > 0);

console.log(res);

该示例创建一个新数组,该数组仅包含正值。

const res = nums.filter(e => e > 0);

filter 方法将一个谓词方法作为参数。谓词返回 true 以保留元素,否则返回 false。

$ nodejs filter_array.js
[ 2, 4, 6, 9 ]

JavaScript 数组 map

map 方法通过将提供的函数应用于调用数组中的每个元素来创建一个新数组。

array_map.js
"use strict";

const a1 = ['dog', 'tree', 'smart'];

const a2 = a1.map(e => e.toUpperCase());
console.log(a2);

我们有一个单词数组。使用 map 方法,我们在每个单词上应用 toUpperCase 方法。

$ nodejs array_map.js
[ 'DOG', 'TREE', 'SMART' ]

JavaScript 数组 find

find 方法返回满足提供的函数的第一个元素的值;否则,将返回 undefined

array_find.js
"use strict";

const nums = [2, -3, 4, 6, 1, 23, 9, 7];

const e1 = nums.find(e => e > 10);
console.log(e1);

在示例中,我们打印大于 10 的第一个值。

$ nodejs array_find.js
23

JavaScript 数组归约

归约 是一种终端操作,它将数组值聚合为单个值。reduce 方法将一个函数应用于累加器和数组中的每个元素(从左到右),以将其归约为单个值。

array_reduce.js
"use strict";

const nums = [2, 3, 4, 5, 6, 7];

const res = nums.reduce((product, next) => product * next);

console.log(res);

我们使用 reduce 方法来计算数组元素的乘积。

const res = nums.reduce((product, next) => product * next);

product 是累加器,next 是数组中的下一个值。

$ nodejs array_reduce.js
5040

来源

JS 数组文档

在本文中,我们介绍了 JavaScript 数组。

作者

我叫 Jan Bodnar,是一位充满激情的程序员,拥有丰富的编程经验。自 2007 年以来,我一直在撰写编程文章。迄今为止,我撰写了 1,400 多篇文章和 8 本电子书。我拥有超过十年的编程教学经验。

查看 所有 JavaScript 教程。