Array
数组是一种类列表对象,它的原型中提供了遍历和修改元素的相关操作。JavaScript 数组的长度和元素类型都是非固定的。因为数组的长度可随时改变,并且其数据在内存中也可以不连续,所以 JavaScript 数组不一定是密集型的,这取决于它的使用方式。
常用方法
some()
测试数组中是不是至少有 1 个元素通过了被提供的函数测试。它返回的是一个 Boolean 类型的值。
``` const array = [1, 2, 3, 4, 5];
// checks whether an element is even const even = (element) => element % 2 === 0;
console.log(array.some(even)); // expected output: true ```
sort()
用原地算法对数组的元素进行排序,并返回数组。默认排序顺序是在将元素转换为字符串,然后比较它们的 UTF-16 代码单元值序列时构建的
``` const months = ['March', 'Jan', 'Feb', 'Dec']; months.sort(); console.log(months); // expected output: Array ["Dec", "Feb", "Jan", "March"]
const array1 = [1, 30, 4, 21, 100000]; array1.sort(); console.log(array1); // expected output: Array [1, 100000, 21, 30, 4] ```
splice()
通过删除或替换现有元素或者原地添加新的元素来修改数组,并以数组形式返回被修改的内容。此方法会改变原数组。
``` const months = ['Jan', 'March', 'April', 'June']; months.splice(1, 0, 'Feb'); // inserts at index 1 console.log(months); // expected output: Array ["Jan", "Feb", "March", "April", "June"]
months.splice(4, 1, 'May'); // replaces 1 element at index 4 console.log(months); // expected output: Array ["Jan", "Feb", "March", "April", "May"] ```
toLocaleString()
返回一个字符串表示数组中的元素。数组中的元素将使用各自的
toLocaleString
方法转成字符串,这些字符串将使用一个特定语言环境的字符串(例如一个逗号 ",")隔开。 ``` const array1 = [1, 'a', new Date('21 Dec 1997 14:12:00 UTC')]; const localeString = array1.toLocaleString('en', { timeZone: 'UTC' });
console.log(localeString); // expected output: "1,a,12/21/1997, 2:12:00 PM", // This assumes "en" locale and UTC timezone - your results may vary ```
toString()
返回一个字符串,表示指定的数组及其元素。
``` const array1 = [1, 2, 'a', '1a'];
console.log(array1.toString()); // expected output: "1,2,a,1a" ```
unshift()
将一个或多个元素添加到数组的开头,并返回该数组的新长度(该方法修改原有数组)。
``` const array1 = [1, 2, 3];
console.log(array1.unshift(4, 5)); // expected output: 5
console.log(array1); // expected output: Array [4, 5, 1, 2, 3] ```
values()
返回一个新的
Array Iterator
对象,该对象包含数组每个索引的值
``` const array1 = ['a', 'b', 'c']; const iterator = array1.values();
for (const value of iterator) { console.log(value); }
// expected output: "a" // expected output: "b" // expected output: "c" ```
另外数组迭代器是一次性的,如下:
const arr = ['a', 'b', 'c', 'd', 'e']; const iterator = arr.values(); iterator.next(); // Object { value: "a", done: false } iterator.next().value; // "b" iterator.next()["value"]; // "c" iterator.next(); // Object { value: "d", done: false } iterator.next(); // Object { value: "e", done: false } iterator.next(); // Object { value: undefined, done: true } iterator.next().value; // undefined
当 next().done=true
或 currentIndex>length
时, for..of
循环结束。
const arr = ['a', 'b', 'c', 'd', 'e']; const iterator = arr.values(); for (let letter of iterator) { console.log(letter); } //"a" "b" "c" "d" "e" for (let letter of iterator) { console.log(letter); } // undefined