JS——思维拓展
1、阶乘求和:4的阶乘是1*2*3*4
<script> function jiechen(value) { var n = 1; for (var i = 1; i <= value; i++) { n *= i; } return n; } function sum(value) { var n = 0; for (var i = 1; i <= value; i++) { n += jiechen(i); } return n; } console.log(sum(3));//9 </script>
2、素数:又称质数,除了1和它本身,不能被其他数整除
<script> function isPrime(num) { for (var i = 2; i < num; i++) { if (num % i === 0) { return false; } } return true; } console.log(isPrime(9));//false </script>
3、将1-10中的奇数放入数组
<script> var arr = []; for (var i = 1; i <= 10; i++) { if (i % 2 !== 0) { arr[arr.length] = i; } } console.log(arr);//[1, 3, 5, 7, 9] </script>
4、将1-10中的偶数放入数组
<script> var arr = []; for (var i = 1; i <= 10; i++) { if (i % 2 === 0) { arr[arr.length] = i; } } console.log(arr);//[2, 4, 6, 8, 10] </script>
5、数组翻转
<script> var arr = ["刘备", "关羽", "张飞", "诸葛亮", "马超", "黄忠", "姜维"]; console.log(arr); var newArr = []; for (var i = 0; i < arr.length; i++) { newArr[newArr.length] = arr[arr.length - 1 - i];//用新数组的长度作为索引值。 } console.log(newArr); </script>
<script> var arr = ["刘备", "关羽", "张飞", "诸葛亮", "马超", "黄忠", "姜维"]; console.log(arr); var newArr = []; for (var i = 0; i < arr.length / 2; i++) { var temp = arr[i]; arr[i] = arr[arr.length - 1 - i];//前面项和对应的后面项交换位置。(arr.length-1-i = 倒数第i+1项) arr[arr.length - 1 - i] = temp; } console.log(arr); </script>
5、递归法计算1-100的值
<script> function getSum(n) { if (n < 1) { return 0; } return n + getSum(n - 1); } console.log(getSum(100));//5050 </script>
6、斐波那契数列:1、1、2、3、5、8、13、21、34、…
<script> var n1 = 1; var n2 = 1; function getNum(num) { for (var i = 3; i <= num; i++) { var temp = n2; n2 = n1 + n2; n1 = temp; } return n2; } console.log(getNum(6));//8 </script>
7、判断闰年:四年一闰而且百年不闰或者四百年一润
<script> function isRun(year) { if (year % 4 === 0 && year % 100 !== 0 || year % 400 === 0) { return true; } return false; } </script>
8、输入年月日,计算这天是当年的第多少天
<script> function isRun(year) { if (year % 4 === 0 && year % 100 !== 0 || year % 400 === 0) { return true; } return false; } function getDay(year, month, day) { var arr = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; for (var i = 0; i < month - 1; i++) { day = day + arr[i]; } if (month > 2 && isRun(year)) { day++; } return day; } console.log(getDay(2017,3,17));//76 </script>