需求場景
最近,本身項目中有一些數組操做,涉及到一些數學集的運算,趁着完成後總結一下。html
簡化問題以後,現有兩數組a = [1, 2, 3]
,b = [2, 4, 5]
,求a,b數組的並集,交集和差集。es6
方法選擇
JS在ES6,ES7以後,新增了一些數組方法,若是可以使用,那是極好的,畢竟本身寫封裝函數仍是比較辛苦的。數組
ES7
ES7新增了一個Array.prototype.includes
的數組方法,用於返回一個數組是否包含指定元素,結合filter方法。瀏覽器
var boolean = array.includes(searchElement[, fromIndex])函數
- // 並集
- let union = a.concat(b.filter(v => !a.includes(v))) // [1,2,3,4,5]
- // 交集
- let intersection = a.filter(v => b.includes(v)) // [2]
- // 差集
- let difference = a.concat(b).filter(v => !a.includes(v) || !b.includes(v)) // [1,3,4,5]
js
ES6
ES6中新增的一個Array.from
方法,用於將類數組對象和可遍歷對象轉化爲數組。只要類數組有length長度,基本均可以轉化爲數組。結合Set結構實現數學集求解。post
Array.from(arrayLike[, mapFn[, thisArg]])ui
- let aSet = new Set(a)
- let bSet = new Set(b)
- // 並集
- let union = Array.from(new Set(a.concat(b))) // [1,2,3,4,5]
- // 交集
- let intersection = Array.from(new Set(a.filter(v => bSet.has(v)))) // [2]
- // 差集
- let difference = Array.from(new Set(a.concat(b).filter(v => !aSet.has(v) || !bSet.has(v)))) // [1,3,4,5]
js
ES5
ES5能夠利用filter和indexOf進行數學集操做,可是,因爲indexOf方法中NaN永遠返回-1,因此須要進行兼容處理。this
- 不考慮NaN(數組中不含NaN)
- // 並集
- var union = a.concat(b.filter(function(v) {
- return a.indexOf(v) === -1})) // [1,2,3,4,5]
- // 交集
- var intersection = a.filter(function(v){ return b.indexOf(v) > -1 }) // [2]
- // 差集
- var difference = a.filter(function(v){ return b.indexOf(v) === -1 }).concat(b.filter(function(v){ return a.indexOf(v) === -1 })) // [1,3,4,5]
js
- 考慮NaN
- var aHasNaN = a.some(function(v){ return isNaN(v) })
- var bHasNaN = b.some(function(v){ return isNaN(v) })
- // 並集
- var union = a.concat(b.filter(function(v) {
- return a.indexOf(v) === -1 && !isNaN(v)})).concat(!aHasNaN & bHasNaN ? [NaN] : []) // [1,2,3,4,5]
- // 交集
- var intersection = a.filter(function(v){ return b.indexOf(v) > -1 }).concat(aHasNaN & bHasNaN ? [NaN] : []) // [2]
- // 差集
- var difference = a.filter(function(v){ return b.indexOf(v) === -1 && !isNaN(v) }).concat(b.filter(function(v){ return a.indexOf(v) === -1 && !isNaN(v) })).concat(aHasNaN ^ bHasNaN ? [NaN] : []) // [1,3,4,5]
js
結語
因爲JS語言的特殊性,NaN在數組的數學集操做中有很多問題,好在ES6和ES7中,新的數組方法解決了部分狀況。單從簡潔性來看,ES7的方法最簡潔明瞭。url
就是不知道新的標準要猴年馬月才能被各大瀏覽器兼容,目前仍是使用Babel比較靠譜。es5