Hey everyone, I have a little question about the way comparison operators work, here’s the code:
var strArr = string.split("");
var revArr = strArr.reverse();
if (strArr.join("") !== revArr.join("")) {
//something
}
That doesn’t go into the //something if block, while if I created the strings first and then compared them like this:
var strArr = string.split("");
newStr = strArr.join("");
var revArr = strArr.reverse();
revStr = revArr.join("");
if (newStr !== revStr) {
//something
}
It would go into the //something if block.
Can anyone clear this up for me? Thanks!
jenovs
January 6, 2017, 7:54pm
2
.reverse()
reverses the original array. So in your first example revArr
and strArr
are the same.
In the second example, you assign to newStr
and then you reverse.
1 Like
I added some console.log debugging to show you what is going on.
var string = "hi";
var strArr = string.split("");
console.log('strArr after split: ' + strArr);
var revArr = strArr.reverse();
console.log('revArr:' + revArr);
console.log('strArr after reverse: ' + strArr);
if (strArr.join("") !== revArr.join("")) {
//something
}
Console
strArr after split: h,i
revArr:i,h
strArr after reverse: i,h
Here is an interactive version of the above.
Thanks! I figured as much after posting the question :shame:
var revArr = strArr.slice(0);
revArr.reverse();
I’m planning on copying the original array into revArr and THEN reversing it, is this the best way to go around doing it?
jenovs
January 6, 2017, 8:12pm
5
Can’t say without seeing the full code and knowing what you are trying to accomplish.
One way is to not use array at all:
var revStr = string.split('').reverse().join('');
if (string !== revStr) {
...
1 Like