本文介紹了期望數組相等,忽略順序的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
限時送ChatGPT賬號..
使用 Jasmine 是否可以測試 2 個數組是否包含相同的元素,但順序不一定相同?即
With Jasmine is there a way to test if 2 arrays contain the same elements, but are not necessarily in the same order? ie
array1 = [1,2,3];
array2 = [3,2,1];
expect(array1).toEqualIgnoreOrder(array2);//should be true
推薦答案
如果只是整數或者其他原始值,可以sort()
比較之前的它們.
If it's just integers or other primitive values, you can sort()
them before comparing.
expect(array1.sort()).toEqual(array2.sort());
如果它的對象,將其與 map()
函數提取將要比較的標識符
If its objects, combine it with the map()
function to extract an identifier that will be compared
array1 = [{id:1}, {id:2}, {id:3}];
array2 = [{id:3}, {id:2}, {id:1}];
expect(array1.map(a => a.id).sort()).toEqual(array2.map(a => a.id).sort());
這篇關于期望數組相等,忽略順序的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!