Array.from()
从一个类似数组或可迭代对象创建一个新的,浅拷贝的数组实例。
-
从String生成数组
Array.from('foo'); // [ "f", "o", "o" ]
-
从Set生成数组
const set = new Set(['foo', 'bar', 'baz', 'foo']); Array.from(set); // [ "foo", "bar", "baz" ]
-
从Map生成数组
const map = new Map([[1, 2], [2, 4], [4, 8]]); Array.from(map); // [[1, 2], [2, 4], [4, 8]] const mapper = new Map([['1', 'a'], ['2', 'b']]); Array.from(mapper.values()); // ['a', 'b']; Array.from(mapper.keys()); // ['1', '2'];
-
从类数组对象(arguments)生成数组
function f() { return Array.from(arguments); } f(1, 2, 3); // [ 1, 2, 3 ]
-
在Array.from中使用箭头函数
Array.from([1,2,3],x=>x+x) //[2,4,6] Array.from({length:5},(v,i)=>i) //[0,1,2,3,4]
-
Sequence generator(range)
const range =(start,stop,step) =>Array.from({length: (stop-start)/step + 1},(_,i) => start+(i*step)); range(0, 4, 1); //[0,1,2,3,4] range(1,10,2); //[1,3,5,7,9] range('A'.charCodeAt(0),'Z'.charCodeAt(0),1).map(x,String.fromCharCode(x)); // ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
-
数组合并去重
function combine(){ let arr=[].concat.apply([],arguments);//没有去重复的新数组 return Array.from(new Set(arr)); } var m=[1,2,2],n=[2,3,3]; combine(m,n) //[1,2,3]
Array.isArray()
确定传递的值是否是一个 Array。返回true/false
// 鲜为人知的事实:其实 Array.prototype 也是一个数组。
Array.isArray(Array.prototype);
Array.of()
创建一个具有可变数量参数的新数组实例,而不考虑参数的数量或类型。
Array.of(7)
//[7]
Array(7)
//[ , , , , , , ]
concat()
用于合并两个或多个数组。此方法不会更改现有数组,而是返回一个新数组。
const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);
//['a','b','c','d','e','f']
合并嵌套数组
var num1=[[1]];
var num2=[2,[3]];
var num3=[5,[6]];
var nums=num1.concat(num2);
//[[1],2,[3]]
var nums2=num1.concat(4,num3);
//[[1],4,5,[6]]
num1[0].push(4);
console.log(nums);
//[[1,4],2,[3]]
copyWithin()
浅复制数组的一部分到同一数组中的另一个位置,并返回它,不会改变原数组的长度。
arr.copyWithin(target[, start[, end]])
- target
索引从0开始,复制到该位置,如果是负数,target将从末尾开始计算。
如果target大于arr.length,将不会发生拷贝。如果target在start之后,复制的序列江北修改以符合arr.length - start
索引从0开始,开始复制的位置。如果是负数,将从末尾开始计算。
如果start被忽略,将从0开始 - end
索引从0开始,复制结束的位置,不包括它。如果是负数,将从末尾开始计算。
如果end被忽略,将一直复制到数组结尾
[1, 2, 3, 4, 5].copyWithin(-2)
// [1, 2, 3, 1, 2]
[1, 2, 3, 4, 5].copyWithin(0, 3)
// [4, 5, 3, 4, 5]
[1, 2, 3, 4, 5].copyWithin(0, 3, 4)
// [4, 2, 3, 4, 5]
[1, 2, 3, 4, 5].copyWithin(-2, -3, -1)
// [1, 2, 3, 3, 4]
[].copyWithin.call({length: 5, 3: 1}, 0, 3);
// {0: 1, 3: 1, length: 5}
entries()
返回一个新的Array Iterator对象,该对象包含数组中每个索引的键/值对。
const array = [1,2,3,4,5]
const iterator = array.entries();
console.log(iterator.next().value);
//[0,1]
console.log(iterator.next().value);
//[1,2]
every()
测试一个数组内的所有元素是否都能通过某个指定函数的测试。它返回一个布尔值。
const isBelowThreshold = (currentValue) => currentValue < 40;
const array1 = [1, 30, 39, 29, 10, 13];
console.log(array1.every(isBelowThreshold));
//true
[12, 5, 8, 130, 44].every(x => x >= 10);
// false
fill()
用一个固定值填充一个数组中从起始索引到终止索引内的全部元素。不包括终止索引。
const array1 = [1, 2, 3, 4];
// fill with 0 from position 2 until position 4
console.log(array1.fill(0, 2, 4));
// expected output: [1, 2, 0, 0]
// fill with 5 from position 1
console.log(array1.fill(5, 1));
// expected output: [1, 5, 5, 5]
console.log(array1.fill(6));
// expected output: [6, 6, 6, 6]
filter()
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);
console.log(result);
//['exuberant','destruction','persent']
find()
返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined。
const array1 = [5, 12, 8, 130, 44];
const found = array1.find(element => element > 10);
console.log(found);
//12
findIndex()
返回数组中满足提供的测试函数的第一个元素的索引。否则返回-1
const array1 = [5, 12, 8, 130, 44];
const isLargeNumber = (element) => element > 13;
console.log(array1.findIndex(isLargeNumber));
//3
flat()
按照一个可指定的深度递归遍历数组,并将所有元素与遍历到的子数组中的元素合并为一个新数组返回。
-
扁平化嵌套数组
var arr1=[1,2,[3,4]]; arr1.flat(); //[1,2,3,4] var arr2=[1,2,[3,4,[5,6]]]; arr2.flat(); //[1,2,3,4,[5,6]] arr2.flat(2); //[1,2,3,4,5,6] //使用 Infinity,可展开任意深度的嵌套数组 var arr=[1,2,[3,4,[5,6,[7,8,[9,10]]]]]; arr.flat(Infinity); //[1,2,3,4,5,6,7,8,9,10]
-
扁平化与数组空项
var arr4 = [1, 2, , 4, 5]; arr4.flat(); // [1, 2, 4, 5]
flatMap()
let arr=["it's Sunny in", "", "California"];
arr.map(x => x.split(' '));
//[["it's Sunny in],[""],["California"]]
arr.flatMap(x => x.split(' '));
//["it's","Sunny","in","","California"]
foreach()
const array1 = ['a', 'b', 'c'];
array1.forEach(element => console.log(element));
//a
//b
//c
includes()
判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true,否则返回false。
第二个参数为开始寻找的起始索引位置
[1, 2, 3].includes(2); // true
[1, 2, 3].includes(4); // false
[1, 2, 3].includes(3, 3); // false
[1, 2, 3].includes(3, -1); // true
[1, 2, NaN].includes(NaN); // true
indexOf()
返回在数组中可以找到一个给定元素的第一个索引,如果不存在,则返回-1。
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
console.log(beasts.indexOf('bison'));
// expected output: 1
// start from index 2
console.log(beasts.indexOf('bison', 2));
// expected output: 4
console.log(beasts.indexOf('giraffe'));
// expected output: -1
join()
将一个数组(或一个类数组对象)的所有元素连接成一个字符串并返回这个字符串。如果数组只有一个项目,那么将返回该项目而不使用分隔符。
如果缺省参数,数组元素用逗号(,)分隔。如果separator是空字符串(""),则所有元素之间都没有任何字符。
const elements = ['Fire', 'Air', 'Water'];
console.log(elements.join());
// expected output: "Fire,Air,Water"
console.log(elements.join(''));
// expected output: "FireAirWater"
console.log(elements.join('-'));
// expected output: "Fire-Air-Water"
keys()
返回一个包含数组中每个索引键的Array Iterator对象。
var arr = ["a", , "c"];
var sparseKeys = Object.keys(arr);
//['0','2']
var denseKeys = [...arr.keys()];
//[0,1,2]
lastIndexOf()
返回指定元素(也即有效的 JavaScript 值或变量)在数组中的最后一个的索引,如果不存在则返回 -1。从数组的后面向前查找,从 fromIndex 处开始。
var array = [2, 5, 9, 2];
var index = array.lastIndexOf(2);
// index is 3
index = array.lastIndexOf(7);
// index is -1
index = array.lastIndexOf(2, 3);
// index is 3
index = array.lastIndexOf(2, 2);
// index is 0
index = array.lastIndexOf(2, -2);
// index is 0
index = array.lastIndexOf(2, -1);
// index is 3
map()
const array1 = [1, 4, 9, 16];
const map1 = array1.map(x => x * 2);
//[2,8,18,32]
pop()
从数组中删除最后一个元素,并返回该元素的值。此方法更改数组的长度。
let myFish = ["angel", "clown", "mandarin", "surgeon"];
let popped = myFish.pop();
console.log(myFish);
// ["angel", "clown", "mandarin"]
console.log(popped);
// surgeon
push()
将一个或多个元素添加到数组的末尾,并返回该数组的新长度。
var sports = ["soccer", "baseball"];
var total = sports.push("football", "swimming");
console.log(sports);
// ["soccer", "baseball", "football", "swimming"]
console.log(total);
//4
var vegetables = ['parsnip', 'potato'];
var moreVegs = ['celery', 'beetroot'];
// 将第二个数组融合进第一个数组
// 相当于 vegetables.push('celery', 'beetroot');
Array.prototype.push.apply(vegetables, moreVegs);
console.log(vegetables);
// ['parsnip', 'potato', 'celery', 'beetroot']
reduce()
对数组中的每个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值。
const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;
array1.reduce(reducer);//1+2+3+4
//10
array1.reduce(reducer,5);//5+1+2+3+4+5
//15
var maxCallback = ( acc, cur ) => Math.max( acc.x, cur.x );
var maxCallback2 = ( max, cur ) => Math.max( max, cur );
// reduce() 没有初始值
[ { x: 2 }, { x: 22 }, { x: 42 } ].reduce( maxCallback ); // NaN
[ { x: 2 }, { x: 22 } ].reduce( maxCallback ); // 22
[ { x: 2 } ].reduce( maxCallback ); // { x: 2 }
[ ].reduce( maxCallback ); // TypeError
// map/reduce; 这是更好的方案,即使传入空数组或更大数组也可正常执行
[ { x: 22 }, { x: 42 } ].map( el => el.x )
.reduce( maxCallback2, -Infinity );
reduceRight()
接受一个函数作为累加器(accumulator)和数组的每个值(从右向左)将其减少为单个值
[[0, 1], [2, 3], [4, 5]].reduceRight((a,b)=>a.concat(b));
//[4,5,2,3,0,1]
reverse()
将数组中元素的位置颠倒,并返回该数组。数组的第一个元素会变成最后一个,数组的最后一个元素变成第一个。该方法会改变原数组。
const a = [1, 2, 3];
console.log(a); // [1, 2, 3]
a.reverse();
console.log(a); // [3, 2, 1]
const a = {0: 1, 1: 2, 2: 3, length: 3};
console.log(a); // {0: 1, 1: 2, 2: 3, length: 3}
Array.prototype.reverse.call(a); //same syntax for using apply()
console.log(a); // {0: 3, 1: 2, 2: 1, length: 3}
shift()
从数组中删除第一个元素,并返回该元素的值。此方法更改数组的长度。
const array1 = [1, 2, 3];
const firstElement = array1.shift();
//1
console.log(array1);//[2,3]
slice()
返回一个新的数组对象,这一对象是一个由 begin 和 end 决定的原数组的浅拷贝(包括 begin,不包括end)。原始数组不会被改变。
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(2));
// ["camel", "duck", "elephant"]
console.log(animals.slice(2, 4));
// ["camel", "duck"]
console.log(animals.slice(1, 15));
// ["bison", "camel", "duck", "elephant"]
some()
测试数组中是不是至少有1个元素通过了被提供的函数测试
如果用一个空数组进行测试,在任何情况下它返回的都是false。
const array = [1, 2, 3, 4, 5];
const even = (element) => element % 2 === 0;
console.log(array.some(even));//true
sort()
排序
const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
//['Dec','Feb','March','Jan']
const array1 = [1, 30, 4, 21, 100];
array1.sort();
//[1,100,21,30,4]
array1.sort((a,b) => a-b);
//[1,4,21,30,100]
splice()
通过删除或替换现有元素或者原地添加新的元素来修改数组,并以数组形式返回被修改的内容。此方法会改变原数组。
const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
//['Jan','Feb','March','April','June']
//从第4位开始删除1个元素,插入'May'
months.splice(4, 1, 'May');
//['Jan','Feb','March','April','May']
toLocaleString()
const array1 = [1, 'a', new Date('21 Dec 1997 14:12:00 UTC')];
const localeString = array1.toLocaleString('en', { timeZone: 'UTC' });
console.log(localeString);
//"1,a,12/21/1997, 2:12:00 PM"
var prices = ['¥7', 500, 8123, 12];
prices.toLocaleString('ja-JP', { style: 'currency', currency: 'JPY' });
// "¥7,¥500,¥8,123,¥12"
unshift()
将一个或多个元素添加到数组的开头,并返回该数组的新长度(该方法修改原有数组)。
const array1 = [1, 2, 3];
console.log(array1.unshift(4, 5));
// 5
console.log(array1);
// [4, 5, 1, 2, 3]