[英]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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.