Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การเปรียบเทียบ Arrays ใน Jasmine.js


อาร์เรย์สามารถเปรียบเทียบได้ 2 แบบ

  • อ้างอิงถึงออบเจ็กต์อาร์เรย์เดียวกันในหน่วยความจำ

  • อาจอ้างอิงถึงออบเจ็กต์ต่างกันแต่เนื้อหาเท่ากันทุกอย่าง

สำหรับกรณีที่ 1 Jasmine มีเมธอด toBe สำหรับตรวจสอบ Reference ตัวอย่างเช่น

ตัวอย่าง

describe("Array Equality", () => {    it("should check for array reference equality", () => {       let arr = [1, 2, 3];       let arr2 = arr       // Runs successfully       expect(arr).toBe(arr2);       // Fails as references are not equal       expect(arr).toBe([1, 2, 3]);    }); });

ผลลัพธ์

จะได้ผลลัพธ์ดังนี้

Array Equality should check for array equality Message:    Expected [ 1, 2, 3 ] to be [ 1, 2, 3 ]. Tip: To check for deep equality, use .toEqual() instead of .toBe().

สำหรับกรณีที่ 2 เราสามารถใช้เมธอด toEqual เพื่อ Deep Compare อาร์เรย์ ตัวอย่างเช่น

ตัวอย่าง

describe("Array Equality", () => {    it("should check for array reference equality", () => {       let arr = [1, 2, 3];       let arr2 = arr;       // Runs successfully       expect(arr).toEqual(arr2);       // Runs successfully       expect(arr).toEqual([1, 2, 3]);    }); });

ผลลัพธ์

จะได้ผลลัพธ์ดังนี้

1 spec, 0 failures