The operator is not equal!= JavaScript doesn't work

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;

        
    }

});
Author: Михаил, 2020-08-13

2 answers

Because they (arr[index].index and index) are the same for you:

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); 
  }
});

This comparison item.symbol == arr[index].symbol is meaningless. item and is 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); 
  }
});
 0
Author: Igor, 2020-08-13 21:01:56

For the given source data, and should not fall into the condition, since the value of the index field of the element matches its index in the array.

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;
  }
});

If you swap the elements, everything works correctly:

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;
  }
});
 0
Author: Grundy, 2020-08-13 20:13:16