假设您要从阵列中选择一首随机歌曲。
var time = ["song1time","song2time","song3time"]
是否可以从不同的数组中选择该元素? 像这样:
angular.module('app', [])
.controller('controller', function($scope) {
$scope.modelValue = 0;
$scope.commaValue = '';
$scope.addComma = function() {
let nStr = '' + $scope.modelValue.replace(',', '');
var x = nStr.split('.');
var x1 = x[0];
var x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
$scope.commaValue = x1 + x2;
}
});
答案 0 :(得分:3)
将Math.floor(Math.random() * songs.length)
的值存储在变量中,并将其值传递给数组。
var songs = ["song1","song2","song3"]
var time = ["song1time","song2time","song3time"]
var index = Math.floor(Math.random() * songs.length);
var randSong = songs[index];
var timeValue = time[index];
console.log(randSong, timeValue);

答案 1 :(得分:3)
如果两个阵列的歌曲顺序相同,那么是。
将随机数存储在单独的变量中,以便可以重复使用。
var randNum = Math.random()
然后用随机变量
替换randSong中的随机生成器var songs = ["song1","song2","song3"]
var randSong = songs[Math.floor( randNum * songs.length)];
然后你可以将它与时间数组一起重复使用。
var time = ["song1time","song2time","song3time"]
var randTime = time[Math.floor( randNum * time.length)];
如果两个阵列没有相同的歌曲顺序,那么你将不得不切换到对象而不是数组。
var songs = {
1:"song1",
2:"song2",
3:"song3"
}
如果你随机选择一首这样的歌:
var randomSong = Object.keys(songs)[Math.floor( Math.random() * Object.keys(songs).length)];
然后,您可以使用randomSong变量识别所需的歌曲。假设你有另一个对象,顺序不同,但键对应同一首歌......
var otherSongs = {
1:"song1",
3:"song3",
2:"song2",
}
使用randomSong变量识别您想要的歌曲,如下所示:
otherSongs[randomSong]
答案 2 :(得分:1)
不要忘记检查数组的大小是否相同,否则如果歌曲超过3个元素,则timeValue可能未定义。
var songs = ["song1","song2","song3"]
var time = ["song1time","song2time","song3time"]
if(time.length === songs.length){
var index = Math.floor(Math.random() * songs.length);
var randSong = songs[index];
var timeValue = time[index];
console.log(randSong, timeValue);
}