如何使用随机值预填充JavaScript数组

时间:2015-01-30 16:15:02

标签: javascript arrays

var cars = ["Saab", "Volvo", "BMW"];
var thisarrayshouldbe = 5;

如何从"汽车预先填充随机值"数组并生成新数组?

1 个答案:

答案 0 :(得分:1)

  

来自cars [...] 数组的随机值为3项...我需要5项

听起来你只想运行一个随机数生成器五次,随机数生成器可以提供012

var cars = ["Saab", "Volvo", "BMW"];

function random_int(max, min) { // max, min inclusive
    min = min | 0; // coerce to int32
    max = max | 0;
    return min + Math.floor(Math.random() * (max - min + 1));
}
// so random_int(2) will produce a value from 0, 1, 2

var i, // iterating variable
    arr = []; // the array being generated

for (i = 4; i >= 0; --i) { // 4 is biggest index in arr length 5
    arr[i] = cars[random_int(cars.length - 1)];
}

// and look at what we've made
arr; // example output: ["Volvo", "Saab", "Saab", "BMW", "Volvo"]