Оператор не равно != JavaScript не срабатывает

let arr = [ { index: 0, symbol: 'а' }, { index: 1, symbol: 'а' } ]

arr.forEach( ( item, index ) => {

    if (item.symbol == arr[index].symbol && arr[index].index != index ){

        console.log(arr[1].symbol);  // почему то сюда  попадает arr[1].symbol;

        
    }

});

Ответы (2 шт):

Автор решения: Igor

Потому что они (arr[index].index и index) у Вас одинаковые:

let arr = [
  { index: 0, symbol: 'а'}, 
  { index: 1, symbol: 'а'}
];

arr.forEach((item, index) => {
  console.log(index, item);
  if (item.symbol == arr[index].symbol && arr[index].index != index) {
    console.log(arr[1].symbol); 
  }
});

Это сравнение item.symbol == arr[index].symbol - бессмысленное. item и есть arr[index].


let arr = [
  { index: 0, symbol: 'а'}, 
  { index: 1, symbol: 'а'}
];

arr.forEach((item, index) => {
  if (arr[0].index != index) { // or if (index != 0) {
    console.log(arr[1].symbol); 
  }
});

→ Ссылка
Автор решения: Grundy

Для приведенных исходных данных и не должно попадать в условие, так как значение поля index элемента совпадает с его индексом в массиве.

let arr = [{
  index: 0,
  symbol: 'а'
}, {
  index: 1,
  symbol: 'а'
}]

arr.forEach((item, index) => {
  console.log('index', index, 'el', arr[index]);
  if (item.symbol == arr[index].symbol && arr[index].index != index) {
    console.log(arr[1].symbol); // почему то сюда не попадает arr[1].symbol;
  }
});

Если поменять местами элементы, все работает правильно:

let arr = [{
  index: 1,
  symbol: 'а'
}, {
  index: 0,
  symbol: 'а'
}, ]

arr.forEach((item, index) => {
  console.log('index', index, 'el', arr[index]);
  if (item.symbol == arr[index].symbol && arr[index].index != index) {
    console.log(arr[1].symbol); // почему то сюда не попадает arr[1].symbol;
  }
});

→ Ссылка