最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

sorting - Javascript sort doesn't work after push? - Stack Overflow

programmeradmin3浏览0评论

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.

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.
Share Improve this question edited Jan 30, 2014 at 14:55 Aravin 4,1081 gold badge24 silver badges39 bronze badges asked Jan 30, 2014 at 14:54 DeanDean 75110 silver badges22 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 10

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 bine Arrays 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]);

As mentioned, for array.push you should pass individual arguments as in the eg:

array.push(1, 5, 10);

But you can do the following to add the content of an array into another array:

Array.prototype.push.apply(array, [1, 5, 10]);

This way, you can pass an array as an argument, since the apply() function transforms the second argument (that must be an array) into individual arguments ;)

发布评论

评论列表(0)

  1. 暂无评论