Can someone confirm if this theory is correct? - Javascript & Arrays
I am learning javascript and really just started - I am using the Firebug Extension in Firefox to try out a few things.
I have set up 2 var(iables) and the 2nd one uses values from the first one:
var multipleValues = [10,20,30,40,50] ;
var reverse = multipleValues.reverse();`
Now I want to pull data from that array via an if statement and create an alert like so:
i开发者_运维百科f (multipleValues [1] == 20) {
alert("Value is there.");
}
else {
alert("Value is not there");
}
Now here is my question - How come when I run the code like this it gives me the "else" option, but when I comment out the var reverse
it comes up as correct?
I thought because I had declared the variable at the start I can access it later on, however using the reverse option seems to be canceling it out?? Am I misunderstanding the theory??
Cheers
The reverse
method modifies the array in place (while also returning the array). Try something like this instead:
var reversed = multipleValues.slice(0).reverse();
Array.reverse() is destructive and changes the original array. It also returns a reference to the array so the two objects should be equal to each other.
reverse()
reverses the array in place.
var x = [1,2,3];
x.reverse();
console.log(x); //Now returns [3,2,1]
So, rather than leaving the original array unmodified, it reverses it. It also returns the value of the reversed array, so both multipleValues
and reverse
are set to the reversed value.
JavaScript can be inconsistent. Some native methods do not modify the caller, and instead return the value (Like, say, String.prototype.split
). Some native methods only modify the caller and don't return a relevant value (Array.prototype.splice
is an example). Some native methods, like this one, Array.prototype.reverse
, do both.
One reliable way to know which does what is to read documentation; I recommend Mozilla Developer Network, which describes reverse()
as such:
The reverse method transposes the elements of the calling array object in place, mutating the array, and returning a reference to the array.
精彩评论