So sánh hai array trong javascript

array,tipjs

Làm thế nào để đánh giá xem hai mảng có bằng nhau không? Có hai cách đó là sử dụng JSON.stringify() hoặc toString(). Nhưng trong hai cách này có một số nguy cơ tiềm ẩn, như là 1 với '1'. Ta có cách này hay hơn.

function equar(a, b) {
    if (a.length !== b.length) {
        return false
    } else {
        for (let i = 0; i < a.length; i++) {
            if (a[i] !== b[i]) {
                return false
            }
        }
        return true;
    }
}
var s = equar([1, '2', 3], [1, 2, 3]);
var t = equar([1, 2, 3], [1, 2, 3]);
console.log(s);  //  false
console.log(t);  //  true

Có thể bạn đã miss một số snippets code

Converting Object to an Array

Converting Object to an Array

try/catch es10

An update for developer convience allows the use of try/catch without an explicit e Error reference in the catch call.

Getting the last element of a split string array

Getting the last element of a split string array

Object.keys và Object.getOwnPropertyNames

Object.keys và Object.getOwnPropertyNames

flatMap()

Use flatMap() creates a new array with sub-array elements flattened by specified depth.