阵列
在上一篇文章中我们提到如何宣告值和取得阵列值,但其实在 JavaScript 中还有很多对阵列的操作方法,例如新增、删除、修改、或过滤阵列值等等,接下来就让我们一一介绍吧。
修改阵列值
语法:
array[index] = 值;
当我们有一阵列,可以直接使用 array[index] = 值
来修改或赋予该位置的值。
let array = [1, 3, 4, 2];array[0] = 5; // 将 array[0] 的值改为 5console.log(array); // [5, 3, 4, 2]
若 array[index]
的 index
超过阵列原有的最大索引值,例如在一个长度为 3 (最大索引值为 2) 的阵列中下 array[4] = 2
,则阵列会自动加长到指定索引值的长度,中间未赋值的项则会为空值。
// 原始阵列长度为 3,最大索引值为 2 (array[2])let array = ["a", "b", "c"];// 指定 array[4]array[4] = "xx";console.log(array); // ['a', 'b', 'c', empty, 'xx']// 阵列加长至 5,第四项未赋值,为空
在阵列最前和最末端加入值
语法:
// 在阵列末端加入一个值array.push(值);// 在阵列末端加入多个值array.push(值, 值, 值); // 以逗号连接// 在阵列最前端加入一个值array.unshift(值);// 在阵列最前端加入多个值array.unshift(值, 值, 值); // 以逗号连接
範例:
let array = ["a", "b", "c"];array.push(1); // 在阵列最后加入 1console.log(array); // ['a', 'b', 'c', 1]array.push("哈", "啰"); // 在阵列最后加入 "哈"、"啰"console.log(array); //['a', 'b', 'c', 1, '哈', '啰']array.unshift(2); // 在阵列最前加入 2console.log(array); // [2, 'a', 'b', 'c', 1, '哈', '啰']
移出阵列最前/后的值
语法:
// 移出阵列最后一项array.pop();// 移出阵列最后一项并赋值到变数中 (原阵列最后一项同样会被删除)let a = array.pop();// 移出阵列第一项array.shift();// 移出阵列第一项并赋值到变数中 (原阵列第一项同样会被删除)let b = array.shift();
範例:
let array = ['a', 'b', 'c', 'd'];let item1 = array.pop(); // 移出最后一项放到变数 item1 中let item2 = array.shift(); // 移出第一项放到变数 item2 中console.log(array); // ['b', 'c'],原始阵列剩下第二项和第三项console.log(item1); // 'd'console.log(item2); // 'a'
删除阵列值
当我们需要删除阵列中的某一项或者某几项时,可以使用 array.splice()
,splice 主要有两个参数,第一个是「开始进行删除的索引值」,第二个参数则是「要删除几项」。
语法:
array.splice(索引值, 要删除几个);
範例:
let array = ['a', 'b', 'c', 'd'];array.splice(1, 2); // 从索引值 1 开始删除两项 (索引 1 和 2)console.log(array); // ['a', 'd']
阵列排序
在阵列中 sort()
可以将阵列中的值进行排序,预设会将元素转型成字串再进行比较,而比较的方式是从左到右依序比对元素中每个字元的 Unicode code point 大小,并将阵列转为由小到大排序。不过由于 sort()
会先将值都转为字串,所以在阵列 [1 , 2, 10, 3]
中,排序后的结果为 [1, 10, 2, 3]
。sort()
其实也可以加参数自定义排序方法,不过目前我们就先知道它能够将阵列由小到大排序就好了。
语法:
array.sort();
範例:
let array = ['d', 'b', 'g', 'd'];array.sort();console.log(array); // ['b', 'd', 'd', 'g']let num = [3, 1, 11, 2, 21];num.sort();console.log(num); // [1, 11, 2, 21, 3]
反转阵列
reverse()
会将阵列反转,也就是原本排列为 [1, 2, 3, 4]
的阵列会变成 [4, 3, 2, 1]
。
语法:
array.reverse();
範例:
let array = ['a', 'b', 'c', 'd'];array.reverse(); // 反转阵列console.log(array); // ['d', 'c', 'b', 'a']
判断是否包含某值
当我们想判断阵列中是否包含某个值时,可以使用 indexOf
或 includes
,前者会回传该项所在的索引值,若不包含则为 -1
,而后者会直接回传是否存在的 Boolean 值。
範例:
let array = ['a', 'b', 'c', 'd'];// indexOfconsole.log(array.indexOf('a')); // 0console.log(array.indexOf('c')); // 2console.log(array.indexOf('z')); // -1 (没有在阵列中)// includesconsole.log(array.includes('c')); // trueconsole.log(array.includes('x')); // false
上一篇:[快速入门前端 50] JavaScript:Array 阵列 (1) 阵列宣告和取值
下一篇:[快速入门前端 52] JavaScript:Object 物件
系列文章列表:[快速入门前端] 系列文章索引列表