Reputation: 1127
I have used:
SpreadsheetApp.getActiveSheet().getRange(... some Range ...).getValues();
to store strings from a spreadsheet's cells into an array. The strings are then compared with other strings, but the comparison (using ==) always fails even though the values are the same.
Browser.msgBox("is '"+topPlayerNames[j]+"' == '"+name+"'? "+(topPlayerNames[j] == name));
// displays:
is 'Data' == 'Data'? false
Why is the javascript comparison failing? Is there hidden formatting in cell values disrupting the comparison?
Upvotes: 0
Views: 7539
Reputation: 3764
Since the getRange() will give you a two dimensional array, By interpreting them something like
var values = SpreadsheetApp.getActiveSheet().getRange(... some Range ...).getValues();
Browser.msgBox(values);
is just output the data in your expected way and exactly not matching with each other. The reason for not matching is your variable container keeps
values = [['a','b',...],['d','f',....]]
. So it will output the data when you ask to out put the data. But when comparing,
Does [['a','b',...]] == 'a','b',... ?? The answer is it is not.
So you need to get out your data from the array to compare with others. In that case use values[0][0] to get 'a' (in my example) or to get 'd', values[1][0] .... and so on. You know element numbers are begin with 0 in javascript array. :)
Now you can compare them. So values[0][0] == 'a' will output TRUE (in my example)
However You didn't mentioned what is topPlayerNames[j], If it is also like values in above, then you need to consider it too in the explained way.
(Your question has limited variables. So I was need to write more when explaining. Next time please give some explained question with respective variable. Use short variables for long statements. That will help to answer in an easy way.)
Upvotes: 1
Reputation: 3700
See What is the correct way to check for string equality in JavaScript?
I would use topPlayerNames[j].equals(name)
I never trust == with strings, as it so often causes a bug.
Upvotes: 0