Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two identical Strings that don't equal each other

Tags:

javascript

Hi I'm having trouble comparing two strings that should really be the same but when I evaluate it in alert(f==g) it evaluates to false.

var oTrackCarriers = {
"9045": [
["A"],
["B"],
["C"]
],
"9046": [
[" "] 
]
};
var oHeadingCarriers = {
"Ripplefold": [
["A"],
["B"],
["C"],
["D"]
],
"PinchPleat": [
["C"],
["D"]
]
};
var HeadingList = oHeadingCarriers["Ripplefold"];
var TrackList = oTrackCarriers["9045"]
var f = (TrackList[0].valueOf());
var g = (HeadingList[0].valueOf());
alert(f);
alert(g);
alert(f == g);

Is this because I'm putting the two values into an array beforehand?

Here's it running http://jsfiddle.net/sQrST/17/embedded/result/ thanks for the help

like image 934
user2661638 Avatar asked Mar 19 '26 02:03

user2661638


2 Answers

var oTrackCarriers = { "9045": [["A"], ["B"], ["C"]],
                       "9046": [[" "]] };

var TrackList = oTrackCarriers["9045"];   // TrackList = [["A"], ["B"], ["C"]]

var f = (TrackList[0].valueOf())          // f =  ["A"]

alert() displays arrays in a non intuitive way, so the fact that f (and g) are arrays is hidden, and comparisons of arrays don't do an element wise comparison of the elements, it compares if the variables reference the same array;

["A"] == ["A"] 
> false

"A" == "A"
> true

a = ['A']
b = a
a == b
> true
like image 112
Joachim Isaksson Avatar answered Mar 20 '26 16:03

Joachim Isaksson


["A"] is an array. You can either get the string value with TrackList[0][0] and HeadingList[0][0] or check if every string contained in TrackList[0] and HeadingList[0] are equals. Usually, two arrays are always differents when comparing them directly. In fact, an array is equal to another if their memory addresses are the same, which makes no sense.

like image 21
Frederik.L Avatar answered Mar 20 '26 17:03

Frederik.L