跳转至

JavaScript 数组

原文: http://zetcode.com/javascript/arrays/

JavaScript 数组教程展示了如何在 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 数组的push()shift()pop()方法。

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);

我们通过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()方法通过在调用数组中的每个元素上应用提供的函数来创建新数组。

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()方法返回满足所提供函数的第一个元素的值; 否则返回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

这是输出。

在本教程中,我们介绍了 JavaScript 数组。 您可能也对这些相关教程感兴趣: Lodash 教程JavaScript 正则表达式Node.js 教程JavaScript 贪食蛇教程


我们一直在努力

apachecn/AiLearning

【布客】中文翻译组