跳转到主要内容
模块 3 · 第 1 课(共 4)课程中的9/32~10 min
模块课程(1/4)

数组:有序列表

数组 是值的有序列表。在 JavaScript 中,元素可以是 彼此不同的类型(尽管在“好的”代码中它们往往是 均质)。它是用方括号写的:

JS
const colori = ['rosso', 'verde', 'blu'];
const misti = [1, 'due', true, null];
const vuoto = [];

按索引读写

指数从 0 开始。最后一个有效索引是 array.length - 1。

JS
const colori = ['rosso', 'verde', 'blu'];
colori[0]; // 'rosso'
colori[2]; // 'blu'
colori[99]; // undefined  ← no error, just undefined
colori.length; // 3

colori[1] = 'giallo'; // now colori is ['rosso', 'giallo', 'blu']
colori[colori.length] = 'x'; // manual push, not recommended

添加和删​​除元素

四个经典方法(push / pop / unshift / shift) 修改 数组就位:

JS
const a = [1, 2, 3];
a.push(4); // a = [1, 2, 3, 4],  returns the new length
a.pop(); // a = [1, 2, 3],     returns the removed element (4)
a.unshift(0); // a = [0, 1, 2, 3],  adds at the head
a.shift(); // a = [1, 2, 3],     removes from the head

包括,搜索

JS
['rosso', 'verde', 'blu'].includes('verde'); // true
['rosso', 'verde', 'blu'].indexOf('blu'); // 2
['rosso', 'verde', 'blu'].indexOf('giallo'); // -1

尝试一下

锻炼#js.m3.l1.e1
尝试:0加载中...

给定数组“numbers = [10, 20, 30, 40]”,使用 length 返回最后一个元素作为最后一个表达式。

正在加载编辑器...
显示提示

最后一个有效索引的长度为 - 1。

3 次尝试后可用的解决方案

复习练习

锻炼#js.m3.l1.e2
尝试:0加载中...

从 `fruits = ['mela', 'pera']` 开始。通过 push 在末尾添加 'banana',然后返回完整数组作为最后一个表达式:['mela','pera','banana']。

正在加载编辑器...
显示提示

Push 会改变数组;你不需要重新分配。

3 次尝试后可用的解决方案