Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
內容目錄
定義一個陣列物件的方法 sameStructureAs,用來比較兩個陣列的巢狀結構是否相同。
舉例來說 [1, 2, 3, [4, 5]] 與 [ 2, 3, 4, [1, 2]] 有一樣的結構。
Array.prototype.sameStructureAs = function (other) {
const that = this;
if ( typeof(that) !== typeof(other) ) return false;
if ( Array.isArray( other ) !== true ) return false;
for ( var i = 0; i < that.length; i++ ){
if ( Array.isArray(that[i]) ) {
if ( that[i].length !== other[i].length ) return false;
return that[i].sameStructureAs( other[i] );
} else {
if ( Array.isArray(other[i]) ) return false;
}
}
return true;
};Array.prototype.sameStructureAs = function (other) {
return (this.length === other.length) ? this.every(function(el, i){
return Array.isArray(el) ? el.sameStructureAs(other[i]) : true;
}) : false;
};這次的解法比較土炮,雖然使用了遞回函式,但還是寫了太多的判斷式。
這裡凸顯了對演算法的差異,最一開始透過 length 的比較,如果兩者都是單一值,則會變成 undefined === undefined,回傳 true。
接著使用了 Array.prototype.every() 這個方法,只要當前元素是單一值,便回傳 true,如果是陣列,則透過遞迴函式的方式再檢查一次。由於 every() 方法必須要全部回傳 true 才會回傳 true,因此如果檢驗的過程中有不符合的狀況,最終的結果便會是 false。