常見的數(shù)組基本用法
1. 數(shù)組的構(gòu)造器有哪幾種?
//第一種:構(gòu)造器方法new Array()
/*
參數(shù):
a.new Array(arg1,arg2,...)參數(shù)長(zhǎng)度為0或者長(zhǎng)度大于等于2時(shí),傳入的參數(shù)將按照順序依次成為新數(shù)組的第0至第N項(xiàng)。
b.new Array(len) len不是Number類型時(shí),返回只包含len元素一項(xiàng)的數(shù)組。
c.new Array(len) len是Number時(shí),返回?cái)?shù)組長(zhǎng)度為len的數(shù)組,最大不超過2的32次方(Math.pow(2,32))
*/
let arr1 = new Array(1,2,3)
console.log(arr1)//[1, 2, 3]
let arr2 = new Array(6)
console.log(arr2)//[empty × 6]
let arr3 = new Array('6')
console.log(arr3)//["6"]
//第二種:Array.of
/*
Array.of方法基本和構(gòu)造器方法一致,唯一區(qū)別是在一個(gè)參數(shù)時(shí),Array.of依然返回?cái)?shù)組元素為該值的一個(gè)數(shù)組。
*/
Array.of(8)//[8]
Array.of(8.0)//[8]
Array.of("8",8)// ["8", 8]
//第三種:Array.from(類似從一個(gè)可迭代對(duì)象中創(chuàng)建一個(gè)新的數(shù)組實(shí)例)
/*
Array.from(arg1,arg2,arg3)
第一個(gè)參數(shù):類數(shù)組對(duì)象,可選
第二個(gè)參數(shù):加工函數(shù),新生成的數(shù)組會(huì)經(jīng)過該函數(shù)的加工再返回。
第三個(gè)參數(shù):this作用域,表示加工函數(shù)執(zhí)行時(shí)的值。
*/
const obj = {0:'a',1:'b',2:'c',length:3}
let newArr = Array.from(obj,function(value,index){
return value.repeat(3)
},obj)
console.log(newArr)// ["aaa", "bbb", "ccc"]
//其他使用
Array.from("abc") //["a", "b", "c"]
Array.from(new Set(['abc','def']))// ["abc", "def"]
Array.from(new Map([[1,'ab'],[2,'cd']]))//[[1, "ab"], [2, "cd"]]
2. 如何判斷一個(gè)數(shù)組?方法有哪些?
const arr = []
//1.instanceof
arr instanceof Array
//2.constructor
arr.constructor === Array
//3.對(duì)象原型鏈Object.prototype.isPrototypeOf
Array.prototype.isPrototypeOf(arr)
//4.getPrototypeOf
Object.getPrototypeOf(arr) === Array.prototype
//5.Object.prototype.toString
Object.prototype.toString(arr) === '[object Array]'
//6.Array.isArray()
Array.isArray(arr)
3. 哪些方法改變數(shù)組自身?
ES5方法:pop push shift unshift reverse sort splice
ES6方法:copyWithin fill
/*
1.pop方法:
定義:末尾刪除元素,返回刪除后的元素
用法:arr.pop()
*/
const array = ["cat", "dog", "cow", "chicken", "mouse"];
let item = array.pop();
console.log(array); // ["cat", "dog", "cow", "chicken"]
console.log(item); // mouse
/*
2.push方法:
定義:末尾添加元素,返回添加元素后數(shù)組的長(zhǎng)度。
用法:arr.push(ele1,ele2,...)
*/
const array = ["football", "basketball", "badminton"];
let i = array.push("golfball");
console.log(array); //["football", "basketball", "badminton", "golfball"]
console.log(i);//4
/*
3.shift方法:
定義:頭部刪除元素,返回被刪除元素。如果數(shù)組為空返回undefined
用法:arr.shift()
*/
const array = [1,2,3,4,5];
let item = array.shift();
console.log(array); // [2,3,4,5]
console.log(item); // 1
/*
4.unshift方法:
定義:頭部添加元素,返回添加元素后,數(shù)組的長(zhǎng)度。
用法:arr.unshift(element1, ..., elementN)
*/
const array = ["red", "green", "blue"];
let length = array.unshift("yellow");
console.log(array); // ["yellow", "red", "green", "blue"]
console.log(length); // 4
/*
5.reverse方法:
定義:對(duì)數(shù)組元素進(jìn)行翻轉(zhuǎn),返回翻轉(zhuǎn)后的數(shù)組,該數(shù)組和原數(shù)組完全相等。
用法:arr.reverse()
*/
const array = [1,2,3,4,5];
let array2 = array.reverse();
console.log(array); // [5,4,3,2,1]
console.log(array2===array); // true
/*
6.sort方法:
定義:對(duì)數(shù)組進(jìn)行排序,返回排序后的數(shù)組,數(shù)組元素為數(shù)字,則正序排列;數(shù)組元素為字母,則按首字母ASCII碼進(jìn)行正序排列;數(shù)組元素為漢字,則按Unicode進(jìn)行排序。
用法:arr.sort(function(a,b){}) a和b分別為用于比較的元素
*/
const array = ["apple","Boy","Cat","dog"];
let array2 = array.sort();
console.log(array); // ["Boy", "Cat", "apple", "dog"]
console.log(array2 == array); // true
//其他妙用
const array1 = [6,10,2,5,4,8]
let arr1 = array1.sort((a,b)=> a - b)//升序排列
console.log(arr1)//[2, 4, 5, 6, 8, 10]
let arr2 = array2.sort((a,b)=> b - a)//降序排列
console.log(arr2)//[10, 8, 6, 5, 4, 2]
/*
7.splice方法:
定義:刪除、替換現(xiàn)有元素或者添加新元素,并返回刪除或修改后的數(shù)組。
用法:arr.splice(start,deleteCount,item1,....item n)
參數(shù):start是要修改的開始位置;deleteCount要?jiǎng)h除的元素的個(gè)數(shù);item為新添加的元素。
*/
const array = ["apple","orange","banana","watermelon"];
//刪除元素
let splices = array.splice(1,1);//從下標(biāo)為1的開始,刪除1個(gè)元素
console.log(array); // ["apple", "banana", "watermelon"]
console.log(splices); // ["orange"]
//替換元素
let replace = array.splice(1,1,'peach')
console.log(array)//["apple", "peach", "banana", "watermelon"]
console.log(replace)//["orange"]
//增加元素
let addItems = array.splice(1,0,'peach','pear')
console.log(array)//["apple", "peach", "pear", "orange", "banana", "watermelon"]
console.log(addItems)//[]
/*
8.copyWithin方法:
定義:從數(shù)組的指定位置拷貝元素到數(shù)組的另一個(gè)指定位置,返回輔助后的數(shù)組,不會(huì)改變?cè)瓟?shù)組的長(zhǎng)度。
用法:arr.copyWithin(target,start,end)
參數(shù):target為復(fù)制元素存放的位置,如果是負(fù)數(shù),target將從末尾開始計(jì)算。target大于數(shù)組長(zhǎng)度則不會(huì)發(fā)生拷貝。
start開始復(fù)制元素的起始位置,如果是負(fù)數(shù),start從末尾開始計(jì)算。
end開始復(fù)制元素的結(jié)束位置,不包含end這個(gè)位置的元素。
*/
const array = [1,2,3,4,5];
let arr = array.copyWithin(0,3);//從下標(biāo)為3的位置開始復(fù)制其后的元素至數(shù)組的起始位置,將4和5復(fù)制到數(shù)組的頭部
console.log(arr); // true [4, 5, 3, 4, 5]
let arr1 = array.copyWithin(1,3,4)
console.log(arr1)//[1, 4, 3, 4, 5]
/*
9.fill方法:
定義:把一個(gè)固定值替換為數(shù)組的元素,返回替換后的數(shù)組。
用法:arr.fill(value,start,end)
參數(shù):value用來填充數(shù)組元素的值
start起始索引
end結(jié)束索引,默認(rèn)值數(shù)組長(zhǎng)度,不包含end索引。
*/
const array = [1,2,3,4,5];
let arr = array.fill(10,0,3);//將數(shù)組0,1,2位置的元素替換為10
console.log(arr);//true [10, 10, 10, 4, 5], 可見數(shù)組區(qū)間[0,3]的元素全部替換為10
4. 哪些方法不改變自身?
ES5:concat join slice toString toLocateString indexOf lastIndexOf
ES7:includes
/*
1.concat方法:
定義:合并數(shù)組,返回合并后的新數(shù)組(哪個(gè)數(shù)組調(diào)用concat方法,那個(gè)數(shù)組的元素在合并后在數(shù)組頭部)。
用法:let newArr = oldArr.concat(arr1,arr2,...)
參數(shù):參數(shù)為被合并的數(shù)組。
*/
const array = [1, 2, 3];
let array2 = array.concat(4,[5,6],[7,8,9]);
console.log(array2); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
console.log(array); // [1, 2, 3], 可見原數(shù)組并未被修改
/*
2.join方法:
定義:把數(shù)組中的所有元素轉(zhuǎn)換成一個(gè)字符串,默認(rèn)以逗號(hào)拼接。
用法:arr.join(separator)
參數(shù):separator為分隔符
*/
const array = ['I', 'love', 'you'];
console.log(array.join()); // ""I,love,you""
console.log(array.join(' ')); // "I love you"
/*
3.slice方法:
定義:從已有數(shù)組中返回選定的元素(從start到end區(qū)間的元素,不包含end)。
用法:arr.slice(start,end)
參數(shù):start和end分別為起始和結(jié)束索引,start默認(rèn)為0,不包含end位置的元素。
start超出數(shù)組索引范圍,則返回空數(shù)組;start為負(fù)數(shù),則從數(shù)組倒數(shù)第幾個(gè)元素開始。
end超數(shù)數(shù)組索引范圍,默認(rèn)截取到末尾;end為負(fù)數(shù),則從數(shù)組倒數(shù)第幾個(gè)元素開始。
*/
const array = ["one", "two", "three","four", "five"];
console.log(array.slice()); // ["one", "two", "three","four", "five"]
console.log(array.slice(2,3)); // ["three"]
console.log(array.slice(-2,-1))//["four"]
/*
4.toString方法:
定義:轉(zhuǎn)換成字符,返回轉(zhuǎn)換后的字符串,數(shù)組元素直接用逗號(hào)拼接。
用法:arr.toString()
*/
const array = ['Jan', 'Feb', 'Mar', 'Apr'];
let str = array.toString();
console.log(str); // Jan,Feb,Mar,Apr
/*
5.toLocaleString方法:
定義:把數(shù)組的元素拼接成一個(gè)元素,數(shù)組中的元素各自使用toLocaleString方法轉(zhuǎn)換成字符串,默認(rèn)逗號(hào)隔開。
用法:arr.toLocaleString(locales,options)
參數(shù):locales帶有標(biāo)記的字符串或字符串?dāng)?shù)組
options可配置對(duì)象(Object,Number,Date)。
*/
const array = [1, 'a', new Date('21 Dec 1997 14:12:00 UTC')];
const localeString = array.toLocaleString('en', { timeZone: 'UTC' });
console.log(localeString);//1,a,12/21/1997, 2:12:00 PM
/*
6.indexOf方法:
定義:返回在數(shù)組中可以找到一個(gè)給定元素的【第一個(gè)索引】,如果不存在,返回-1。
用法:arr.indexOf(searchElement,fromIndex)
參數(shù):searchElement要查找的元素
fromIndex開始查找的位置
*/
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
console.log(beasts.indexOf('bison'));// 1
console.log(beasts.indexOf('bison',2));//4
/*
7.lastIndexOf方法:
定義:返回指定元素在數(shù)組中的【最后一個(gè)索引】,如果不存在返回-1。
用法:arr.lastIndexOf(searchElement,fromIndex)
參數(shù):searchElement要查找的元素
fromIndex開始查找的逆向位置,默認(rèn)為數(shù)組長(zhǎng)度減1。
*/
const animals = ['Pig', 'Tiger', 'Dog', 'Pig'];
console.log(animals.lastIndexOf('Pig'));// 3
console.log(animals.lastIndexOf('Pig',2))//0
/*
8.includes方法:
定義:用來判斷一個(gè)數(shù)組是否包含一個(gè)指定的值,如果有返回true,否則返回false。(比較字符串時(shí)區(qū)分大小寫)
用法:arr.includes(item,fromIndex)
參數(shù):item需要查找的元素的值(字符串區(qū)分大小寫)
fromIndex開始查找索引位置
*/
const numbers = [1,2,3,2]
console.log(numbers.includes(2))//true
console.log(numbers.includes(3,-1))//false
5. 遍歷的方法有哪些?
ES5:forEach every some filter map reduce reduceRight
ES6:entries find findIndex keys values
/*
1.forEach方法:
定義:對(duì)數(shù)組的每個(gè)元素執(zhí)行一個(gè)給定的函數(shù),返回值undefined。不能終止循環(huán),除非拋出異常。
用法:arr.forEach(function(currentValue,index,array){})
參數(shù):currentValue正在處理的元素
index正在處理的元素的索引
array正在操作的數(shù)組
*/
const arr = ['a','b','c','d']
const newArr = []
let resp = arr.forEach((ele,idx)=>{
newArr[idx] = ele.toUpperCase()
})
console.log(newArr)//["A", "B", "C", "D"]
console.log(resp)//undefined
/*
2.every方法:
定義:測(cè)試數(shù)組內(nèi)的所有元素是否都能通過某個(gè)指定的函數(shù)。返回Boolean。如果一個(gè)元素返回false,則立即返回false,不在繼續(xù)執(zhí)行。(若為空數(shù)組,直接返回true)
用法:arr.every(function(element,index,array){})
參數(shù):element用于測(cè)試的元素
index用于測(cè)試的元素的索引
array調(diào)用every的當(dāng)前數(shù)組
*/
const arr = [2,4,6,8,10]
let resp = arr.every((ele,idx)=>{
return ele % 2 === 0
})
console.log(resp)//true
const arr1 = [2,4,6,9,10]
let resp1 = arr1.every((ele,idx)=>{
console.log(idx)//0,1,2,3 未打印4
return ele % 2 === 0
})
console.log(resp1)//false
/*
3.some方法:
定義:測(cè)試數(shù)組中是不是至少有一個(gè)元素通過了指定函數(shù),返回Boolean。如有滿足條件的值,立即返回(若為空數(shù)組,直接返回false)
用法:arr.some(function(element,index,array){})
參數(shù):element正在處理的元素
index正在處理的元素的索引
array調(diào)用some的數(shù)組
*/
const arr = [1,2,3,4,5]
let resp = arr.some((ele,idx)=>{
console.log(idx)//0,1,2 有滿足條件的值,立即返回
return ele >= 3
})
console.log(resp)//true
/*
4.filter方法:
定義:測(cè)試數(shù)組中的所有元素是否通過了指定函數(shù),返回一個(gè)新數(shù)組。如果沒有任何元素通過,則返回空數(shù)組。
用法:arr.filter(function(element,index.array){})
參數(shù):element正在處理的元素
index正在處理的元素的索引
array調(diào)用filter的數(shù)組
*/
const words = ['spray', 'limit', 'elite', 'destruction', 'present'];
const result = words.filter((ele,idx)=>{
return ele.length > 6
});
console.log(result);//["destruction", "present"]
/*
5.map方法:
定義:為數(shù)組的每一個(gè)元素都執(zhí)行一次指定的函數(shù),返回一個(gè)新數(shù)組。
用法:arr.map(function(element,index,array){})
參數(shù):element正在處理的元素
index正在處理的元素的索引
array調(diào)用filter的數(shù)組
*/
const sqrts = [9,16,25]
const nums = sqrts.map((ele,idx)=>{
return Math.sqrt(ele)
})
console.log(nums)// [3, 4, 5]
/*
6.reduce方法:
定義:為數(shù)組中的每一個(gè)元素都執(zhí)行指定函數(shù),將其匯總的結(jié)果單個(gè)返回(從左往右)。
用法:arr.reduce(function(accumulator, currentValue, index, array), initialValue])
第一個(gè)參數(shù):回調(diào)函數(shù),四個(gè)參數(shù),分別為:回調(diào)返回的初始值(如果沒有初始值,則為數(shù)組第一個(gè)元素的值),數(shù)組中正在處理的元素,正在處理的元素的索引,調(diào)用reduce的原數(shù)組。
第二個(gè)參數(shù):為回調(diào)返回值的初始值。
*/
//基礎(chǔ)用法:
const arr = [0, 1, 2, 3, 4]
let result = arr.reduce((prev, current,idx) =>{
console.log(prev, current,idx)//0 1 1 1 2 2 3 3 3 6 4 4
//初始值默認(rèn)為數(shù)組第一個(gè)元素,索引則會(huì)從1開始,不是第0 。
return prev + current
});//無初始值
console.log(result)//10
let result1 = arr.reduce((prev, current,idx) =>{
console.log(prev, current,idx)//10 0 0 10 1 1 11 2 2 13 3 3 16 4 4
return prev + current
},10);//初始值為10
console.log(result1)//20
//進(jìn)階用法:
//a.二位數(shù)組轉(zhuǎn)一維數(shù)組
const arr = [[0, 1], [3, 2], [4, 5]]
let result = arr.reduce((prev,current,idx)=>{
return prev.concat(current)
},[])
console.log(result)//[0, 1, 3, 2, 4, 5]
//b.計(jì)算數(shù)組中每個(gè)元素出現(xiàn)的次數(shù)
const names = ['Alice','Bob','Tiff','Bruce','Alice','Tom']
let result = names.reduce((allNames,name)=>{
if(name in allNames){
allNames[name]++
}else{
allNames[name] = 1
}
return allNames
},{})
console.log(result)//{Alice: 2, Bob: 1, Tiff: 1, Bruce: 1, Tom: 1}
//c.根據(jù)屬性對(duì)object進(jìn)行分類
const peoples = [
{ name: 'Alice', age: 20 },
{ name: 'Max', age: 30 },
{ name: 'Max', age: 40 },
{ name: 'Tom', age: 50}
];
let groupByProperty = (arrs,property)=>{
return arrs.reduce((acc,current)=>{
let key = current[property]
if(!acc[key]){
acc[key] = []
}
acc[key].push(current)
return acc
},{})
}
let result = groupByProperty(peoples,'name')
console.log(result)//{"Alice":[{"name":"Alice","age":20}],"Max":[{"name":"Max","age":30},{"name":"Max","age":40}],"Tom":[{"name":"Tom","age":50}]}
/*
7.reduceRight方法:
定義:為數(shù)組中的每一個(gè)元素都執(zhí)行指定函數(shù),將其匯總的結(jié)果單個(gè)返回(從右往左)。
用法:arr.reduce(function(accumulator, currentValue, index, array), initialValue])
第一個(gè)參數(shù):回調(diào)函數(shù),四個(gè)參數(shù),分別為:回調(diào)返回的初始值(如果沒有初始值,則為數(shù)組最后一個(gè)元素的值),數(shù)組中正在處理的元素,正在處理的元素的索引,調(diào)用reduce的原數(shù)組。
第二個(gè)參數(shù):為回調(diào)返回值的初始值。
*/
const arr = [[0, 1], [3, 2], [4, 5]]
let result = arr.reduceRight((prev,current,idx)=>{
return prev.concat(current)
},[])
console.log(result)//[4, 5, 3, 2, 0, 1]
/*
8.find方法:
定義:返回滿足條件的第一個(gè)元素的值,否則返回undefined。
用法:arr.find((ele,idx,array))
*/
const arr = [5, 12, 8, 130, 44];
const result = arr.find((ele,idx,array)=>{
console.log(idx) //0 1
return ele > 10
});
console.log(result);//12
/*
9.findIndex方法:
定義:返回滿足條件的第一個(gè)元素的索引,沒找到返回-1。
用法:arr.findIndex((ele,idx,array))
*/
const arr = [5, 12, 8, 130, 44];
const idx = arr.findIndex((ele,idx,array)=>{
console.log(idx) //0 1
return ele > 10
});
console.log(idx);//1
/*
10.entries方法:
定義:返回一個(gè)新的Array Iterator對(duì)象,包含[key,value]鍵值對(duì)。有一個(gè)next方法。
用法:arr.entries()
*/
const arr = ['1','2','3','4','5']
let iterator = arr.entries()
console.log(iterator)//Array Iterator {}
console.log(iterator.next())//{"value": [0,"1"],"done": false}
//next.done 用于指示迭代器是否完成:在每次迭代時(shí)進(jìn)行更新而且都是false,直到迭代器結(jié)束done才是true。
//拓展
for(let e of iterator){
//循環(huán)之前不要調(diào)用next方法哦,不然迭代器會(huì)從最后一次開始執(zhí)行。
console.log(e)//[0, "1"] [1, "2"] [2, "3"] [3, "4"] [4, "5"]
}
/*
11.keys方法:
定義:返回一個(gè)包含數(shù)組鍵的Array Iterator對(duì)象。
用法:arr.keys()
*/
const arr = ['a', 'b', 'c']
const iterator = arr.keys();
for (const key of iterator) {
console.log(key); //0 1 2
}
/*
12.values方法:
定義:返回一個(gè)包含數(shù)組每個(gè)索引值的Array Iterator對(duì)象。
用法:arr.values()
*/
const arr = ['a', 'b', 'c']
const iterator = arr.values();
for (const value of iterator) {
console.log(value);//a b c
}
| 方法 | 返回值 | 是否改變?cè)瓟?shù)組 | 指定函數(shù)是否需要return | 遍歷元素個(gè)數(shù) |
|---|---|---|---|---|
| forEach | undefined | 否 | 否 | 所有元素 |
| every | true/false | 否 | 是 | 所有元素 |
| some | true/false | 否 | 是 | 滿足條件 |
| filter | 新數(shù)組 | 否 | 是 | 所有元素 |
| map | 新數(shù)組 | 是 | 是 | 所有元素 |
| reduce | 單個(gè)返回值 | 否 | 是 | 所有元素 |
| reduceRight | 單個(gè)返回值 | 否 | 是 | 所有元素 |
| find | 滿足條件第一個(gè)元素 | 否 | 是 | 滿足條件 |
| findIndex | 滿足條件第一個(gè)元素的索引 | 否 | 是 | 滿足條件 |
6. 其他數(shù)組方法
數(shù)組扁平化:flat flatMap
/*
1.flat方法:
定義:按照指定深度遞歸遍歷數(shù)組,并將所有元素合并到一個(gè)新數(shù)組返回。
用法:arr.flat(depth)
參數(shù):depth為深度,默認(rèn)為1。
*/
const arr = [1, 2, [3, 4, [5, 6]]];
let flat = arr.flat(Infinity)
console.log(flat)//[1, 2, 3, 4, 5, 6]
/*
2.flatMap方法:
定義:使用指定函數(shù)映射每個(gè)元素,返回壓縮后的新數(shù)組。該方法效果等同于flat深度為1。
用法:arr.flatMap(function(currentValue,index,array))
參數(shù):指定回調(diào)函數(shù)
*/
const arr = [[2], [4], [6], [8]]
let str = arr.flatMap((currentValue)=>{
return currentValue
})
console.log(str)// [2, 4, 6, 8]
評(píng)論
圖片
表情
