skip to Main Content

Here, this is a really simple app.
I just expect it to log "Yes", not "No, array is something else" here.

import React, { useEffect, useState } from "react";
import { View } from "react-native";

function Test(props) {
  const [array, setArray] = useState([1, 2, 3]);

  if (array === [1, 2, 3]) {
    console.log("Yes");
  } else {
    console.log("No, array is something else");
  }

  return <View></View>;
}

export default Test;

However, it actually logs the second one "No, array is something else".
Because the array of the state [1, 2, 3] was exactly equal to [1, 2, 3], I thought that would just show the first console.log("Yes")

I don’t know what’s going on here, or am I missing something?
It’d be nice if someone could give me some advice on it.
Thank you in advance

2

Answers


  1. In javascript [1, 2, 3]===[1, 2, 3] will return false even if two arrays are equal.

    Try this,

     if (JSON.stringify(array).toString() == JSON.stringify([1, 2, 3]).toString()) {
        console.log('Yes1');
      } else {
        console.log('No, array is something else');
      }
    

    It will return true

    Login or Signup to reply.
  2. This one also works

     if (array.toString() == [1, 2, 3].toString()) {
        console.log('Yes1');
      } else {
        console.log('No, array is something else');
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search