簡體   English   中英

如何使用angularjs從數組中隨機取n個元素?

[英]How to take random n elements from array using angularjs?

我有一個包含元素列表的數組。

app.controller("MainController", function($scope){
    $scope.names= [
        {
            value: "q1"
        },
        {
            value: "q2"
        },
        {
            value: "q3"
        }
    ];
});

我需要隨機取兩個元素並分配給一個新數組。 我能怎么做?

您必須僅使用 javascript 來完成此操作。 因為 AngularJS 不是一種編程語言。

看一下這個:

if (!Math.getRandomValueBetween) {
    Math.getRandomValueBetween = function (from, to) {
        return Math.floor(Math.random() * (to - from + 1) + from);
    };
}
//USAGE -- Math.getRandomValueBetween(100,1000) //950


if (!Array.prototype.getRandom) {
    Array.prototype.getRandom = function () {
        return this[Math.getRandomValueBetween(0, this.length - 1)];
    };
}
//USAGE -- [1,34,56,76,9,67,5].getRandom();

來自 KnightCoder 要點

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM