random()方法
1 function selectFrom(lowerValue, upperValue) {
2 var choices = upperValue - lowerValue + 1;
3 return Math.floor(Math.random() * choices + lowerValue);
4 }
5
6 var num = selectFrom(2, 10);
7 console.log(num);
8
9 var colors = ["red", "green", "blue", "yellow", "black", "purple", "brown"];
10 var color = colors[selectFrom(0, colors.length - 1)];
11 console.log(color);
2 var choices = upperValue - lowerValue + 1;
3 return Math.floor(Math.random() * choices + lowerValue);
4 }
5
6 var num = selectFrom(2, 10);
7 console.log(num);
8
9 var colors = ["red", "green", "blue", "yellow", "black", "purple", "brown"];
10 var color = colors[selectFrom(0, colors.length - 1)];
11 console.log(color);