JS返回值练习
程序员文章站
2024-02-19 08:02:16
...
效果图
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>返回值练习</title>
<style type="text/css">
output{
white-space: pre;
}
</style>
</head>
<body>
<input type="text" name="" id="" value="" />
<button type="button" οnclick="getJc()">求阶乘</button>
<button type="button" οnclick="getSum()">求阶乘和</button>
<button type="button" οnclick="checkNum()">判断是否为素数</button>
<br />
<output id="opt"></output>
<script type="text/javascript">
//求阶乘
//5!==5x4x3x2x1
var ipt_=document.querySelector("input");
var opt_=document.querySelector("output");
//验证是否为素数
function checkNum(){
var num=ipt_.value;
if(num.match(/\D+/)){
alert("请输入数字");
}else{
if(getCheck(num)){
opt_.innerText="true";
}else{
opt_.innerText="false";
}
}
}
function getCheck(num){
for(var i=2;i<num;i++){
if(num%i==0){
return false;
}
}
return true;
}
//求阶乘
function getJc(){
var num=ipt_.value;//字符串
if(/\d+\!{1}/.test(num)){//这个感叹号要注意中英文的切换
var num_jc=Number(/\d+/.exec(num)[0]);//数字
var product=1;
var process='';
for(var i=num_jc;i>0;i--){
if(i==1){
process+=i;
}else{
process+=i+"*";
}
product*=i;
}
opt_.innerText=process+"="+product;
}else{
alert("请输入正确格式");
}
}
//求阶乘和
function getSum(){
var num=ipt_.value;
// var text_node;
if(/\d+\!{1}/.test(num)){
var num_jcsum=Number(/\d+/.exec(num)[0]);//数字
var process_sum='';
var count=0;
var product;
var process;
// var count_pre="";
for(var i=num_jcsum;i>0;i--){
product=1;
process='';
for(var j=i;j>0;j--){
if(j==1){
process+=j;
}else{
process+=j+"*";
}
product*=j;
}
process_sum+=process+"="+product+"\n";
count+=product;
// console.log(count);
// console.log(process_sum);
}
opt_.innerText=process_sum+"\n"+"总和为:"+count;
}else{
alert("请输入正确格式");
}
}
</script>
</body>
</html>