一攀唯、生成一個(gè)類(lèi)似[1-100]的數(shù)組;
思路: 生成一個(gè)length
是100的數(shù)組 , 循環(huán)數(shù)組添加值
1.1利用fill
方法填充值進(jìn)數(shù)組,map
循環(huán)數(shù)組添加index
值
let arr = new Array(100).fill(0).map((item,index)=>index+1)
1.2利用Array.from()
方法
Array.from()
方法從一個(gè)類(lèi)似數(shù)組或可迭代對(duì)象創(chuàng)建一個(gè)新的洁桌,淺拷貝的數(shù)組實(shí)例。(詳情看上一篇)
const buildArray = Array.from(Array(100),(v,k)=>k+1)
二侯嘀、數(shù)組淺拷貝;
const arr = [1, 2, 3]
const arrClone = [...arr]
// 對(duì)象也可以這樣淺拷貝
const obj = { a: 1 }
const objClone = { ...obj }
三另凌、數(shù)組合并;
const arr1 = [1, 2, 3]
const arr2 = [4, 5, 6]
const arr3 = [7, 8, 9]
const arr = [...arr1, ...arr2, ...arr3]
arr1.concat(arr2, arr3)//也可以合并
四、數(shù)組去重;
這里只寫(xiě)最新的最簡(jiǎn)單快捷的數(shù)組去重的方法,
new Set(arr)
接受一個(gè)數(shù)組參數(shù)并生成一個(gè)set結(jié)構(gòu)的數(shù)據(jù)類(lèi)型戒幔。set數(shù)據(jù)類(lèi)型的元素不會(huì)重復(fù)且是Array Iterator
吠谢,所以可以利用這個(gè)特性來(lái)去重。
const arr = [1, 1, 2, 2, 3, 4, 5, 5]
const newArr = [...new Set(arr)]
五溪食、數(shù)組取交集;
const a = [0, 1, 2, 3, 4, 5]
const b = [3, 4, 5, 6, 7, 8]
const last= [...new Set(a)].filter(item => b.includes(item))
// [3, 4, 5]
六囊卜、數(shù)組取差集;
const a = [0, 1, 2, 3, 4, 5]
const b = [3, 4, 5, 6, 7, 8]
const diffValues = [...new Set([...a, ...b])].filter(item => !b.includes(item) || !a.includes(item)) // [0, 1, 2, 6, 7, 8]
七、數(shù)組轉(zhuǎn)對(duì)象;
const arr = [1, 2, 3, 4]
const newObj = {...arr} // {0: 1, 1: 2, 2: 3, 3: 4}
const obj = {0: 0, 1: 1, 2: 2, length: 3}
// 對(duì)象轉(zhuǎn)數(shù)組不能用展開(kāi)操作符错沃,因?yàn)檎归_(kāi)操作符必須用在可迭代對(duì)象上
let newArr = [...obj] // Uncaught TypeError: object is not iterable...
// 可以使用Array.form()將類(lèi)數(shù)組對(duì)象轉(zhuǎn)為數(shù)組
let newArr = Array.from(obj) // [0, 1, 2]
八栅组、數(shù)組常用遍歷;
8.1 檢測(cè)數(shù)組是否有元素符合判斷條件;
const arr = [1, 2, 3, 4, 5]
const hasNum = arr.some(item => typeof item === 'number')
8.2 檢測(cè)數(shù)組所有元素是否都符合判斷條件;
const arr = [1, 2, 3, 4, 5]
const isAllNum = arr.every(item => typeof item === 'number')
8.3 找到第一個(gè)符合條件的元素/下標(biāo);
const arr = [1, 2, 3, 4, 5]
const findItem = arr.find(item => item === 3) // 返回子項(xiàng)
const findIndex = arr.findIndex(item => item === 3) // 返回子項(xiàng)的下標(biāo)
九、數(shù)組中的reduce
使用時(shí)機(jī);
8.1 假如有如下每個(gè)元素都由字母's'加數(shù)字組成的數(shù)組arr枢析,現(xiàn)在找出其中最大的數(shù)字:(arr不為空)
//題目
const arr = ['s0', 's4', 's1', 's2', 's8', 's3'];
//常規(guī)操作
const last = Math.max(...arr.map(item=>parseInt(item.replace('s',''))));
console.log(last);//8
//reduce操作
const maxS = arr.reduce((prev, cur) => {
const curIndex = Number(cur.replace('s', ''))
return curIndex > prev ? curIndex : prev
}, 0)