0

Напишите функцию compare для сравнения двух объектов по ссылке. Если передать функции две ссылки на один и тот же объект, она должна возвращать true, иначе — false.

function compare(firstObj, secondObj) {
    // напишите ваш код здесь
}

const first = {
  property: 'value'
};

const second = {
  property: 'value'
};

const third = second;

compare(first, second); // false
compare(second, third); // true 

Вот мое решение:

function compare(firstObj, secondObj) {
  if ( firstObj === secondObj ) return true;
    

  if ( ! ( firstObj instanceof Object ) || ! ( secondObj instanceof Object ) ) return false;
   

  if ( firstObj.constructor !== secondObj.constructor ) return false;
   

  for ( var p in firstObj ) {
    if ( ! firstObj.hasOwnProperty( p ) ) continue;
     

    if ( ! secondObj.hasOwnProperty( p ) ) return false;
      

    if ( firstObj[ p ] === secondObj[ p ] ) continue;
      

    if ( typeof( firstObj[ p ] ) !== "object" ) return false;
    

    if ( ! object_equals( firstObj[ p ],  secondObj[ p ] ) ) return false;
   
  }

  for ( p in secondObj )
    if ( secondObj.hasOwnProperty( p ) && ! firstObj.hasOwnProperty( p ) )
      return false;
   

  return true;
}


const first = {
  property: 'value'
};

const second = {
  property: 'value'
};

const third = second;

console.log(compare(first, second)); // false
console.log(compare(second, third)); // true

еще решала так

function isEqual(firstObj, secondObj) {
  const a = JSON.stringify(firstObj);
  const b = JSON.stringify(secondObj);
  if(a == b){
    return true
  } else {
    return false
  }
}

const first = {
  property: 'value',
  anotherProperty: 'another value'
};

const second = {
  property: 'value',
  anotherProperty: 'another value'
};

const third = {
  property: 'value',
  anotherProperty: 'one more value'
};

console.log(isEqual(first, second));
console.log(isEqual(second, third))

isEqual(first, second); // true
isEqual(second, third); // false

Все равно выдает ошибкую, в обоих вариантахю помогите, пожалуйста.

2
  • 1
    Смотрите deep compare stackoverflow.com/questions/1068834/… и syncfusion.com/blogs/post/… 25 ноя 2022 в 2:08
  • «Если передать функции две ссылки на один и тот же объект, она должна возвращать true, иначе — false» — так это же обычное сравнение объектов. return firstObj === secondObj и всё.
    – Alexey Ten
    25 ноя 2022 в 9:06

2 ответа 2

1

const compare = (firstObj, secondObj) => firstObj === secondObj;

const first = {property: 'value'};
const second = {property: 'value'};
const third = second;

console.log(
compare(first, second), // false
compare(second, third) // true 
);

0
function compare(firstObj, secondObj) {
if (firstObj === secondObj){
  return true
}
  else{
      return false

  }
}
1
  • Ваш ответ можно улучшить с помощью дополнительной информации. Пожалуйста, нажмите править для добавления подробностей, например, цитат или документации, чтобы другие могли подтвердить правильность вашего ответа. Вы можете найти дополнительную информацию о том, как писать хорошие ответы в Справке. 27 мар в 6:12

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.