【数组练习题】
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script type="text/javascript" src="math.js"></script>
<script type="text/javascript">
/*
1、 创建一个长度为10的数组,给数组元素随机赋值(0-10)。然后用3种方式遍历数组,输出为质数的数组元素。
*/
var arr = new Array(10);
for (var i = 0; i < arr.length; i++) {
arr[i] = parseInt(Math.random()*11);
//判断arr[i]是否是质数
}
console.log(arr);
for (var i = 0; i < arr.length; i++) {
//判断arr[i]是否是质数
if ( isPrime(arr[i]) ) {
console.log(arr[i]);
}
}
</script>
2、 随机生成一个五位以内的数,然后输出该数共有多少位,每位分别是什么
<script type="text/javascript">
// //12345
// 12345%10-->5
// var num = parseInt(12345/10)
// num(1234) %10-->4
// num = parseInt(num(1234)/10) //123
// //123
var num = parseInt( Math.random()*10000000 );
//1234 5
// num%10-->5--->存入数组
// num = parseInt(num/10) 1234
// num==0 退出循环
//num=12345
console.log("num = "+num);
var arr = [];
while(num!=0){
arr.push(num%10);//[5,4,3,2,1]
num = parseInt(num/10);//num=0
}
console.log("这是一个"+arr.length+"位数"+"从高位到低位的数字分别是"+arr.reverse());
</script>
3、开发一个标题为“FlipFlop”的游戏应用程序。它从1计数到100,遇到3的倍数就替换为单词“Flip”,5的倍数就替换为单词“Flop”,既为3的倍数又为5的倍数则替换为单词“FlipFlop”。
<script type="text/javascript">
var arr = new Array(100);
for (var i = 0; i < arr.length; i++) {
arr[i] = i+1;
}
for (var i = 0; i < arr.length; i++) {
if (arr[i]%3==0&&arr[i]%5==0) {
arr[i] = "FlipFlop";
}
if(arr[i]%3==0){
arr[i] = "Flip";
}
if(arr[i]%5==0){
arr[i] = "Flop";
}
}
console.log(arr);
</script>
<br/>
5、生成13位条形码
Ean-13码规则:第十三位数字是前十二位数字经过计算得到的校验码。
例如:690123456789
第十三位计算其校验码的过程为:
@前十二位的奇数位和6+0+2+4+6+8=26 i%2==0
@前十二位的偶数位和9+1+3+5+7+9=34 i%2!=0
@将奇数和与偶数和的三倍相加26+34*3=128
@取结果的个位数:128的个位数为8
@用10减去这个个位数10-8=2
所以校验码为2(注:如果取结果的个位数为0,那么校验码不是(10-0=10),而是0)实现方法ean13()计算验证码,输入12位条码,返回带验证码的条码。
例如:输入:692223361219输出:6922233612192
<script type="text/javascript">
var arr = new Array(13);
// var arr = [6,9,0,1,2,3,4,5,6,7,8,9]
for (var i = 0; i < arr.length-1; i++) {
arr[i] = parseInt(Math.random()*10);
}
//奇数位和 偶数位和
var jSum = 0,oSum = 0;
for (var i = 0; i < arr.length-1; i++) {
if (i%2==0) {
jSum+=arr[i];
}else{
oSum+=arr[i];
}
}
var ret = 10-(jSum+oSum*3)%10;
if( ret==10 ){
arr[12] = 0;
}else{
arr[12]=ret;
}
console.log("验证码是"+arr);
</script>
6、随机生成验证码。验证码的格式如:A2MC
<script type="text/javascript">
var arr = [1,2,3,4,5,6,7,8,9,0,"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
// var sum = 0;
var str = "";
for (var i = 0; i < 4; i++) {
var index = parseInt(Math.random()*arr.length);
str+=arr[index]
}
console.log(str);
</script>
</body>
</html>