What am I doing wrong here: Same results in IE9 and FF.
function TestArrayOperationsClick()
{
function sortNums(a, b)
{
return a - b;
}
var array = [6, 4, 2, 8];
console.log("Array 1: " + array);
array.sort(sortNums);
console.log("Sort 1: " + array);
array.push([1, 5, 10]);
console.log("Array 2: " + array);
array.sort(sortNums);
console.log("Sort 2: " + array);
}
Output:
LOG: Array 1: 6,4,2,8
LOG: Sort 1: 2,4,6,8
LOG: Array 2: 2,4,6,8,1,5,10
LOG: Sort 2: 2,4,6,8,1,5,10 <- not sorted.
For array.push(...)
, you should be passing individual arguments, not an array:
array.push(1, 5, 10);
For which the final output would then be:
Sort 2: 1,2,4,5,6,8,10
Otherwise, the result of your push is actually this:
[2,4,6,8,[1,5,10]]
, though it's not showing clearly when you do console.log
.
Edit: As Jonathan mentioned, if you're looking to append an array of items, .concat()
is the way to go.
.push()
doesn't combine Array
s like the following appears to expect:
array.push([1, 5, 10]);
Instead of pushing the individual values, it pushes the 2nd Array
itself, resulting in:
[ 2, 4, 6, 8, [ 1, 5, 10 ] ]
To append one Array
onto another, you can use .concat()
:
array = array.concat([1, 5, 10]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With