Javascript Array equals(arr)

Description

Javascript Array equals(arr)


Array.prototype.equals = function(arr) {
  var len = arr.length;
  if (this.length !== len) {
    return false;
  }/*  w  ww  .j  av a  2  s.com*/

  for (var i = 0; i < len;i ++) {
    if (this[i] !== arr[i]) {
      return false;
    }
  }

  return true;
};


var arr = [1, 2, 3];
var arr2 = [1, 2, 3];

var bol = arr.equals(arr2);
console.log(bol); // true

Javascript Array equals(arr)

Array.prototype.equals = function (arr) {
  const len = this.length//from  w  ww . j  a v a2 s .com
  if (len !== arr.length) {
    return false
  }
  for (let i = 0; i < len; i++) {
    if (this[i] !== arr[i]) {
      return false
    }
  }
  return true
}

const a = [1, 2].equals([1, 2]) // true
const b = [1, 2].equals([0]) // false

console.log(a, b)

Javascript Array equals(arr)

Array.prototype.equals = function(arr) {
  const len = this.length//from www .  j av a  2s.c om
  if (len !== arr.length) {
    return false
  }
  for (let i = 0; i < len; i++) {
    if (this[i] !== arr[i]) {
      console.log(222,this[i])
      return false
    }
  }
  return true
}
console.log([1, 2].equals([1, 2]))
// => true
console.log([1, 2].equals([0]))
// => false

Javascript Array equals(arr)

/*/*from   w  ww  . j  a va  2s  .co  m*/
 * Check if two arrays are equal.
 * Works even on nested arrays.
 * Usage:
 *     >> [1, [2, [3, 4]]].equals([1, [2, [3, 4]]]
 *     true
 */
Array.prototype.equals = function (arr) {
 if (this.length != arr.length) return false;
 return this.reduce(function (acc, el, i) {
 if (_.isArray(el)) return acc && el.equals(arr[i]);
 return acc && el === arr[i];
}, true)};



PreviousNext

Related