已解決:如何隨機排序數組 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] = “數字”;

相關文章:

發表評論