/*** Return a random element from an array that is* different than `last` (as long as the array has > 1 items).* Return null if the array is empty.*/function getRandomDifferent(arr, last = undefined) {if (arr.length === 0) {return null;} else if (arr.length === 1) {return arr[0];} else {let num = 0;do {num = Math.floor(Math.random() * arr.length);} while (arr[num] === last);return arr[num];}}
像这样实现:
const arr = [1,2,3];const r1 = getRandomDifferent(arr);const r2 = getRandomDifferent(arr, r1); // r2 is different than r1.
$scope.ctx.skills = data.result.skills;$scope.praiseTextArray = ["Hooray","You\'re ready to move to a new skill","Yahoo! You completed a problem","You\'re doing great","You succeeded","That was a brave effort trying new problems","Your brain was working hard","All your hard work is paying off","Very nice job!, Let\'s see what you can do next","Well done","That was excellent work","Awesome job","You must feel good about doing such a great job","Right on","Great thinking","Wonderful work","You were right on top of that one","Beautiful job","Way to go","Sensational effort"];
$scope.praiseTextWord = $scope.praiseTextArray[Math.floor(Math.random()*$scope.praiseTextArray.length)];
//For Search textbox random valuevar myPlaceHolderArray = ['Hotels in New York...', 'Hotels in San Francisco...', 'Hotels Near Disney World...', 'Hotels in Atlanta...'];var rand = Math.floor(Math.random() * myPlaceHolderArray.length);var Placeholdervalue = myPlaceHolderArray[rand];
alert(Placeholdervalue);
function getArrayRandomElement (arr) {if (arr && arr.length) {return arr[Math.floor(Math.random() * arr.length)];}// The undefined will be returned if the empty array was passed}
用法:
// Example 1var item = getArrayRandomElement(['January', 'February', 'March']);
// Example 2var myArray = ['January', 'February', 'March'];var item = getArrayRandomElement(myArray);
Array.prototype.random = function(n){if(n&&n>1){const a = [];for(let i = 0;i<n;i++){a.push(this[Math.floor(Math.random()*this.length)]);}return a;} else {return this[Math.floor(Math.random()*this.length)];}}
const mySampleArray = ['a','b','c','d','e','f','g','h'];
mySampleArray.random(); // return any random value etc. 'a', 'b'mySampleArray.random(3); //retun an array with random values etc: ['b','f','a'] , ['d','b','d']
alert(mySampleArray.random());alert(mySampleArray.random(3));