JavaScript 는 두 배열 의 내용 이 같은 지 비교 합 니 다(추천)
alert([]==[]);  // false
alert([]===[]);  // falseJavaScript 에서 Array 는 대상 이기 때문에=또는==조작 자 는 두 대상 이 같은 인 스 턴 스 인지,즉 같은 대상 이 인용 하 는 지 비교 할 수 있 습 니 다.현재 자 바스 크 립 트 는 내 장 된 연산 자가 없 으 며 대상 의 내용 이 같은 지 판단 합 니 다.
그러나 관성 사 고 는 수조 도 값 이 라 고 생각 하고 비교 할 수 있다.
배열 이 같은 지 비교 하려 면 배열 요 소 를 옮 겨 다 니 며 비교 할 수 밖 에 없다.
인터넷 에 널리 알려 진 방법 중 하 나 는 배열 을 문자열 로 바 꾸 는 것 이다.
JSON.stringify(a1) == JSON.stringify(a2)
a1.toString() == a2.toString()이런 방법 은 어떤 경우 에는 가능 하 다.두 배열 의 요소 순서 가 같 고 요소 가 모두 문자열 로 바 뀔 수 있 는 상황 에서 확실히 가능 하 다.그러나 이러한 코드 는 위험 이 존재 한다.예 를 들 어 숫자 가 문자열 로 바 뀌 고 숫자'1'과 문자열'1'은 같다 고 여 겨 져 디 버 깅 에 어려움 을 초래 할 수 있 으 므 로 추천 하지 않 는 다.
StackOverflow 에서 큰 신 이 정확 한 방법 을 제 공 했 으 니 짐꾼 을 하 겠 습 니 다.
// Warn if overriding existing method
if(Array.prototype.equals)
  console.warn("Overriding existing Array.prototype.equals. Possible causes: New API defines the method, there's a framework conflict or you've got double inclusions in your code.");
// attach the .equals method to Array's prototype to call it on any array
Array.prototype.equals = function (array) {
  // if the other array is a falsy value, return
  if (!array)
    return false;
  // compare lengths - can save a lot of time 
  if (this.length != array.length)
    return false;
  for (var i = 0, l = this.length; i < l; i++) {
    // Check if we have nested arrays
    if (this[i] instanceof Array && array[i] instanceof Array) {
      // recurse into the nested arrays
      if (!this[i].equals(array[i]))
        return false;    
    }      
    else if (this[i] != array[i]) { 
      // Warning - two different object instances will never be equal: {x:20} != {x:20}
      return false;  
    }      
  }    
  return true;
}
// Hide method from for-in loops
Object.defineProperty(Array.prototype, "equals", {enumerable: false});
Object.prototype.equals = function(object2) {
  //For the first loop, we only check for types
  for (propName in this) {
    //Check for inherited methods and properties - like .equals itself
    //https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty
    //Return false if the return value is different
    if (this.hasOwnProperty(propName) != object2.hasOwnProperty(propName)) {
      return false;
    }
    //Check instance type
    else if (typeof this[propName] != typeof object2[propName]) {
      //Different types => not equal
      return false;
    }
  }
  //Now a deeper check using other objects property names
  for(propName in object2) {
    //We must check instances anyway, there may be a property that only exists in object2
      //I wonder, if remembering the checked values from the first loop would be faster or not 
    if (this.hasOwnProperty(propName) != object2.hasOwnProperty(propName)) {
      return false;
    }
    else if (typeof this[propName] != typeof object2[propName]) {
      return false;
    }
    //If the property is inherited, do not check any more (it must be equa if both objects inherit it)
    if(!this.hasOwnProperty(propName))
     continue;
    //Now the detail check and recursion
    //This returns the script back to the array comparing
    /**REQUIRES Array.equals**/
    if (this[propName] instanceof Array && object2[propName] instanceof Array) {
          // recurse into the nested arrays
      if (!this[propName].equals(object2[propName]))
            return false;
    }
    else if (this[propName] instanceof Object && object2[propName] instanceof Object) {
          // recurse into another objects
          //console.log("Recursing to compare ", this[propName],"with",object2[propName], " both named \""+propName+"\"");
      if (!this[propName].equals(object2[propName]))
            return false;
    }
    //Normal value comparison for strings and numbers
    else if(this[propName] != object2[propName]) {
      return false;
    }
  }
  //If everything passed, let's say YES
  return true;
} 이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
[2022.04.19] 자바스크립트 this - 생성자 함수와 이벤트리스너에서의 this18일에 this에 대해 공부하면서 적었던 일반적인 함수나 객체에서의 this가 아닌 오늘은 이벤트리스너와 생성자 함수 안에서의 this를 살펴보기로 했다. new 키워드를 붙여 함수를 생성자로 사용할 때 this는...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.