JS數組數據的重組,過濾,篩選,拼接方法

filter() 數組重組方法 https://www.runoob.com/cssref/css3-pr-filter.html
indexOf() 篩選數組方法 http://www.w3school.com.cn/jsref/jsref_indexOf.asp
concat() 數組拼接方法 http://www.w3school.com.cn/jsref/jsref_concat_array.asp
includes() 包含 https://www.runoob.com/jsref/jsref-includes.html
filter,indexOf兩個函數方法,在項目中我們經常用來過濾數據,或者重組數據,其他的也可以用for循環,forEach,$.each來循環過濾

ES6寫法

filter() 重組數組的數據很好用

test(){
			let m=this;
			let arr1=[1,2,3];
			let arr2=arr1.filter((v,i)=>{
				return v!='2'
			})			
			console.log(arr2)//數據返回[1,3]			
},

indexOf() 篩選數組方法

test(){
			let arr1=[
				[1,2,3],
				[2,2,3],
				[1,4,3],
				[1,2,6]
			];
			let arr3=[]
			arr1.forEach((v,i)=>{
				if(v.indexOf(4)!=-1){
					arr3.push(v)
				}
			})
			console.log(arr3)//數據返回有4的數組[1,4,3]
},

concat() 把多個數組連接在一起

test(){
	let arr1=[1,2,3]
	let arr2=[4,5,6]
	let arr3=[7,8,9]
	let arr4=[1,2,12]
	let test=[]
	test=test.concat(arr1).concat(arr2).concat(arr3).concat(arr4)
	console.log(test)//數據返回[1,2,3,4,5,6,7,8,9,1,2,12]
}

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

結合運用

取兩個數組的並集

	let test1 = [1, 2, 3]
	let test2 = [2, 4, 5]
	let arr= test1.concat(test2.filter(v => !test1.includes(v)))
	console.log(arr)// 數據返回 [1,2,3,4,5]

取兩個數組的交集

	let test1 = [1, 2, 3]
	let test2 = [2, 4, 5]
	let arr=test1.filter(v => test2.includes(v))
	console.log(arr)// 數據返回 [2]

取兩個數組的差集

	let test1 = [1, 2, 3]
	let test2 = [2, 4, 5]
	let arr=test1.concat(test2).filter(v => test1.includes(v) && !test2.includes(v))
	console.log(arr)// 數據返回 [1,3]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章