ES6語法——數組擴展

數組擴展
數組新增特性
  • Array.from
  • Array.of
  • copyWithin
  • find / findIndex
  • fill
  • entries / keys / values 遍歷相關
  • includes
{
	//Array.of
	let arr = Array.of(1,2,4,5,6);
	console.log('arr=', arr)//[1,2,4,5,6]
	let empty = Array.of()
	console.log('empty',empty)//[]
}
{
	//Array.from 把僞數組或集合轉化爲數組
	let p = document.querySelectorAll('p');//集合
	//元素的集合不是數組,無法使用數組的方法
	let pArr = Array.from(p);//轉化成數組
	pArr.forEach(function(item,index){
		console.log(item.textContent)//textContent文本內容的方法
	})
	//傳入兩個參數,類似map的映射,第二個參數是函數,函數起到map的作用
	//遍歷數組每一項,然後返回新的數組
	console.log(Array.from([1,3,5],function(item){return item+2}));//[3,5,7]
}
{
	//fill 填充數組
	//數組全部替換成7
	console.log('fill-7',[1,'a',undefined].fill(7));//[7,7,7]
	//數組按照規定長度進行替換
	//第一個參數:替換成什麼
	//第二個參數:從數組哪個位置開始比如 0 ,1 ,2(索引值index)
	//第三個參數:在數組的哪個位置結束 (數組長度length)
	console.log('fill,pos',["a","b","c","d","e"].fill(7,1,3));
	//["a", 7, 7, "d", "e"]
}
{
	//entries / keys / values *遍歷相關*
	//只取keys下標值 能兼容
	for(let index of ['1','c','ks'].keys()){
		console.log('keys',index)//打印數組下標
		//0
		//1
		//2
	}
	//只取value值 存在兼容,需要polyfill
	for(let value of ['1','c','ks'].values()){
		console.log('values', value)//打印數組value值
		//'1'
		//'c'
		//'ks'
	}
	//既取index又取value 全兼容
	for(let [index,value] of ['1','c','ks'].entries()){
		console.log('index+values',index,value)//打印index,value
		//0 '1'
		//1 'c'
		//2 'ks'
	}
}
{
	//copyWithin 當前數組內部,把指定位置的成員複製到其他位置上
	//第一個參數:從哪個位置開始替換 0,1,2
	//第二個參數:從哪個位置開始讀取 0,1,2
	//第三個參數:從哪個位置截止(不包含該位置) 0,1,2 
	console.log([1,2,3,4,5].copyWithin(0,3,4))//[4,2,3,4,5]
	console.log([1,2,3,4,5].copyWithin(0,3))//[4, 5, 3, 4, 5]
	console.log([1,2,3,4,5].copyWithin(0,2,5))//[3, 4, 5, 4, 5]	
}
{
	//find findIndex 只找第一個符合條件的值
	//判斷數組中是否包含某個元素,es5裏要麼遍歷,要麼使用underscore工具庫 
	//find返回的是第一個值
	console.log([1,2,3,4,5,6].find(function(item){return item > 3}))//4
	console.log([1,2,3,4,5,6].find(function(item){return item > 9}))//undefined
	//findIndex返回的是index下標
	console.log([1,2,3,4,5,6].findIndex(function(item){return item > 3}))//3 
	console.log([1,2,3,4,5,6].findIndex(function(item){return item > 9}))//-1
}
{
	//includes 解決了個NaN非數字的變量 ,功能類似於find findIndex
	//數組中是否包含1,能遍歷NaN
	console.log('number',[1,2,NaN].includes(1))//true
	//數組中是否包含NaN,es5中是不能將NaN與NaN做相等運算的,
	console.log('number',[1,2,NaN].includes(NaN))//true	
	
}
發佈了46 篇原創文章 · 獲贊 7 · 訪問量 5484
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章