Underscore.js是一個JavaScript庫,提供了許多有用的函數,即使在不使用任何內置對象的情況下,也可以極大地幫助您進行編程,例如映射,過濾,調用等。
_.shuffle()函數用於以隨機方式排列數組列表。 _.shuffle()下劃線函數使用Fisher Yates Shuffle,這將在下麵提到的文章中進行討論。因此,每次使用此函數時,根據Fisher Yates Shuffle,此函數的輸出都會有所不同。
用法:
_.shuffle(list)
參數:該函數接受單個參數列表。此參數用於保存將被拖曳的項目列表。
返回值:返回的值是新的隨機數組,其中包含原始數組中傳遞給_.shuffle()函數的所有元素。
將數字數組傳遞給_.shuffle()函數:._shuffle()函數將列表中的元素一個接一個地進行,並根據Fisher Yates Shuffle進行指定的操作。然後console.log()最終答案,它將包含隨機問題中原始數組的所有元素。
例:
<html>
<head>
<script src =
"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" >
</script>
</head>
<body>
<script type="text/javascript">
console.log(_.shuffle(_.shuffle([1, 2, 3, 4, 5, 6])));
</script>
</body>
</html>
輸出:
將結構傳遞給_.shuffle()函數:將結構傳遞給_.shuffle()函數。首先,將數組聲明為“目標”,然後將此數組傳遞給_.shuffle()函數。 “目標”數組的元素及其所有屬性都將被拖曳。
例:
<html>
<head>
<script src =
"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" >
</script>
</head>
<body>
<script type="text/javascript">
var goal = [
{
"category" : "other",
"title" : "harry University",
"value" : 50000,
"id":"1"
},
{
"category" : "traveling",
"title" : "tommy University",
"value" : 50000,
"id":"2"
},
{
"category" : "education",
"title" : "jerry University",
"value" : 50000,
"id":"3"
},
{
"category" : "business",
"title" : "Charlie University",
"value" : 50000,
"id":"4"
}
]
console.log(_.shuffle(goal));
</script>
</body>
</html>
輸出:
將一個屬性為true /false的列表傳遞給_.shuffle()函數:首先聲明數組(此處的數組為“ people”)。選擇一種需要檢查的條件,例如“ hasLongHairs”。 Console.log的最終答案。最終的答案將是一個隨機數組,因為費舍爾·耶茨·沙夫在算法中使用了隨機函數。
例:
<html>
<head>
<script src =
"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" >
</script>
</head>
<body>
<script type="text/javascript">
var people = [
{"name": "sakshi", "hasLong": "false"},
{"name": "aishwarya", "hasLong": "true"},
{"name": "akansha", "hasLong": "true"},
{"name": "preeti", "hasLong": "true"}
]
console.log(_.shuffle(people, 'name'));
</script>
</body>
</html>
輸出:
聲明一個數組,然後將其傳遞給_.shuffle()函數:聲明一個數組,讓“用戶”將其屬性設置為“ num”,然後將其傳遞給_.shuffle()函數。然後console.log新的隨機數組。每次您運行輸出時,輸出都會不同。
例:
<html>
<head>
<script src =
"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" >
</script>
</head>
<body>
<script type="text/javascript">
var users = [{"num":"1"}, {"num":"2"}, {"num":"3"}, {"num":"4"}, {"num":"5"}];
console.log(_.shuffle(users, 'id'));
</script>
</body>
</html>
輸出:
相關用法
- d3.js d3.shuffle()用法及代碼示例
- p5.js shuffle()用法及代碼示例
- PHP shuffle()用法及代碼示例
- JQuery first()用法及代碼示例
- JQuery on()用法及代碼示例
- JQuery after()用法及代碼示例
- JQuery last()用法及代碼示例
- JQuery one()用法及代碼示例
- JQuery val()用法及代碼示例
- JQuery eq()用法及代碼示例
- underscore.js map()用法及代碼示例
- underscore.js min()用法及代碼示例
- underscore.js _.without()用法及代碼示例
- underscore.js where()用法及代碼示例
- underscore.js _.last()用法及代碼示例
注:本文由純淨天空篩選整理自Sakshi98大神的英文原創作品 Underscore.js | shuffle() with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。