繁体   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