user2202843
user2202843

Reputation: 13

If statement fails even when the variables match

I am trying to make a program that organizes punch-ins from an RFID scanner in google sheets...

When I go to match scan [i] with employee name [j] it never succeeds.

I have a simple if statement:

//names[i] is the name of the card for the scan event (card names = employee full name)
var name = names[i];

//the j for loop will check all employee names in the list for a match
var employee = employees[j];
if (name==employee) {
  var ifsuccess = true;
}

But I never get ifsuccess to = true... it may be obvious but I have never done programming in google script before (or javascript :P) does anyone know what I've done wrong?

screenshot

Upvotes: 1

Views: 872

Answers (4)

Bergi
Bergi

Reputation: 664528

In your debugger you can see that both name and employee refer to arrays with a string in it - yet those are two distinct arrays (with different internal ids), which are therefore not equal in terms of ==.

If you want to compare the strings inside them, use

var ifsuccess = name[0] == employee[0];

Upvotes: 0

guessimtoolate
guessimtoolate

Reputation: 8642

Using toString method might help as well:

name.toString()==employee.toString()

But the other suggestions look cleaner.

Upvotes: 0

Spencer Lockhart
Spencer Lockhart

Reputation: 1174

> foo = ['foo'];
[ 'foo' ]
> bar = ['foo'];
[ 'foo' ]
> foo == bar
false
> foo === bar
false

Comparing array to array- even if they look the same, will not be true unless they are really referencing the same array in memory.

> bar = foo;
[ 'foo' ]
> foo == bar
true
> foo === bar
true

So, try comparing strings instead:

if (bar[0] === foo[0])

Upvotes: 0

Matt Coughlin
Matt Coughlin

Reputation: 18906

It looks like you're comparing two Array objects rather than two strings. The screenshot claims that name and employee are indexed arrays with a single element.

To compare the string data inside each Array object:

name[0] == employee[0]     // equal value

Or the slightly safer:

name[0] === employee[0]    // equal value and of the same type

Upvotes: 1

Related Questions