首页 > 技术文章 > js 数组常用知识点

-LemonWater- 2021-12-01 10:31 原文

1、从类数组对象创建数组

// 字符串
'hello'.split('');   // ['h', 'e', 'l', 'l', 'o']
[...'hello']; // ['h', 'e', 'l', 'l', 'o']
Array.from('hello');  // ['h', 'e', 'l', 'l', 'o']

// map
const map = new Map([[1, 2], [2, 4], [4, 8]]);
Array.from(map);  // [1, 2], [2, 4], [4, 8]
[...map];  // [1, 2], [2, 4], [4, 8]

// arguments
function createArray() { return Array.from(arguments); }
function createArray() { return [...arguments]; }
createArray(1, 2, 3, 4, 5) // [1, 2, 3, 4, 5]

// iterator
function* iterator() {
  yield 1;
  yield 2;
}
console.log([..iterator()]); // [1, 2]
console.log(Array.from(iterator())); // [1, 2]

2、初始化一个数组

new Array(5).fill(0);   //(5) [0, 0, 0, 0, 0]
Array.from({length: 5}, x => 0);   //(5) [0, 0, 0, 0, 0]

3、克隆一个数组

[].concat([1,2,3,4,5]);  //(5) [1, 2, 3, 4, 5]
[1,2,3,4,5].slice();  //(5) [1, 2, 3, 4, 5]
Array.from([1,2,3,4,5]);    //(5) [1, 2, 3, 4, 5]

4、查找数组的唯一项

let arr = [1,2,3,3]
arr.filter((e,i)=>{
	if(arr.indexOf(e)==i)
		return e;
});  //(3) [1, 2, 3]
[...new Set(arr)];  //(3) [1, 2, 3]
Array.from(new Set(arr));   //(3) [1, 2, 3]

5、获取数组最大值

Math.max(...[1,2,3,4]) //4

6、创建范围函数

function Range(start, stop, step) {
	// 只有一个参数
	if(!stop && !step) {stop = start; start = 0;}
	// 有两个参数
	if(!step) step=1;
	return Array.from({ length: (stop - start) / step + 1}, (e, i) => start + (i * step));
}

console.log(Range(5)) //(6) [0, 1, 2, 3, 4, 5]
console.log(Range(0,5)) //(6) [0, 1, 2, 3, 4, 5]
console.log(Range(0,5,1)) // (6) [0, 1, 2, 3, 4, 5]
console.log(Range(0,9,3)) // (4) [0, 3, 6, 9]
console.log(Range('A'.charCodeAt(0), 'Z'.charCodeAt(0), 1).map(x => String.fromCharCode(x)));
//(26) ['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']

参考链接: https://mp.weixin.qq.com/s/7fAJmmWGLB59rsWmNCBQGg

推荐阅读