已解决:如何随机排序数组 javascript

随机排序数组的主要问题是它可能非常耗时。

 arrays sorting random

I have an array of objects that I need to randomly sort.  The objects have a property called "order" that is a number.  I need to sort the array so that the order property is in random order, but the other properties of each object stay in place.  How can I do this?


A:

You can use <code>sort</code> with a function that returns a random value:


<code>const arr = [
  { id: 1, name: 'foo' },
  { id: 2, name: 'bar' },
];
arr.sort(() =&gt; Math.random() - 0.5);
console.log(arr);</code>



数组和排序函数

数组是可以使用索引号访问的数据集合。 数组中的第一个元素位于索引 0,第二个元素位于索引 1,依此类推。 要访问数组中的第三个元素,您可以使用索引号 3。

要对数组进行排序,可以使用排序函数。 排序函数有两个参数:一个数组和一个比较函数。 比较函数比较数组中的两个元素并返回一个布尔值。 如果比较函数返回 true,则数组中位置 x 的元素将被放置在数组中位置 y 的元素之前。 如果比较函数返回 false,则数组中位置 x 的元素将被放置在数组中位置 y 的元素之后。

以下是如何使用排序函数对数字数组进行排序的示例:

可变数字 = [1, 2, 3, 4]; // 使用比较函数对数字进行排序 var sortedNumbers = numbers .sort(function(a, b) { return a – b; }); // 打印出 sortedNumbers console .log(sortedNumbers);

随机数组

数组是可以使用索引号访问的数据集合。 在 JavaScript 中,数组是使用 Array 构造函数创建的。

要创建一个空数组,请使用 Array() 构造函数:

var myArray = new Array();

要创建包含五个元素的数组,请使用以下代码:

var myArray = 新数组(5);

myArray[0] = “JavaScript”; myArray[1] = “数组”; myArray[2] = “函数”; myArray[3] = “字符串”; myArray[4] = “布尔值”; myArray[5] = “数字”;

相关文章:

发表评论