简体   繁体   English

推送后Javascript排序不起作用?

[英]Javascript sort doesn't work after push?

What am I doing wrong here: Same results in IE9 and FF. 我在这里做错了什么:在IE9和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(...) ,您应该传递单个参数,而不是数组:

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 . 虽然在执行console.log时没有清楚地显示。

Edit : As Jonathan mentioned, if you're looking to append an array of items, .concat() is the way to go. 编辑 :正如Jonathan所提到的,如果你想要追加一系列项目, .concat()就是你要走的路。

.push() doesn't combine Array s like the following appears to expect: .push()不会像以下那样组合Array

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

Instead of pushing the individual values, it pushes the 2nd Array itself, resulting in: 它不是推送单个值,而是推送第二个Array本身,导致:

[ 2, 4, 6, 8, [ 1, 5, 10 ] ]

To append one Array onto another, you can use .concat() : 要将一个Array附加到另一个Array ,可以使用.concat()

array = array.concat([1, 5, 10]);

As mentioned, for array.push you should pass individual arguments as in the eg: 如上所述,对于array.push您应该传递单个参数,例如:

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 ;) 这样,您可以将数组作为参数传递,因为apply()函数将第二个参数(必须是数组)转换为单个参数;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM