本课题要求:
when run(3) return 'Fizz'
when run(5) return 'Buzz'
when run(7) return 'Whizz'
when run(3 * 5) return 'FizzBuzz' //run 的参数为 3和5共同的倍数
when run(3 * 7) return 'FizzWhizz' //run 的参数为 3和7共同的倍数
when run(5 * 7) return 'BuzzWhizz' //run 的参数为 5和7共同的倍数
when run(3 * 5 * 7) return 'FizzBuzzWhizz' //run 的参数为 3、5和7共同的倍数
其余情况:
when run(n) return n // n 可以为 非 3、5、 7或3、5、7的倍数的数字 如:run(2) return '2'
由此可知,本课题要求在特殊条件下更改程序的返回值。由于js语言进行字符串操作的简易性,不难想到利用此特性来对参数做相应修改。而是否满足相应条件则可通过if语句来判断。
主要代码(附注释):
function run(num) { var f=0,b=0,w=0; //定义用于判断的变量f,b,w if(num%3==0) f=1; if(num%5==0) b=1; if(num%7==0) w=1; //根据参数num满足的条件改动变量f,b,w的值 if(f==1||b==1||w==1)//如果不满足以上任一条件,则不对参数num本身作任何改动 { num='';//先使num成为空字符串 if(f) num +='Fizz'; if(b) num +='Buzz'; if(w) num +='Whizz'; //依据f,b,w的值对num作相应修改 } return num.toString(); }
调试结果:
完整代码:
function run(num) { var f=0,b=0,w=0; if(num%3==0) f=1; if(num%5==0) b=1; if(num%7==0) w=1; if(f==1||b==1||w==1) { num=''; if(f) num +='Fizz'; if(b) num +='Buzz'; if(w) num +='Whizz'; } return num.toString(); } document.write('') var test1 = function() { let result = run(2); if(result != 2) { document.write('The test 1 failed') }else { document.write('The test 1 result is : '+ result) } } test1() document.write("
") var test2 = function() { let result = run(3); if(result != 'Fizz') { document.write('The test 2 failed') }else { document.write('The test 2 result is : '+ result) } } test2() document.write("
") var test3 = function() { let result = run(5); if(result != 'Buzz') { document.write('The test 3 failed') }else { document.write('The test 3 result is : '+ result) } } test3() document.write("
") var test4 = function() { let result = run(7); if(result != 'Whizz') { document.write('The test 4 failed') }else { document.write('The test 4 result is : '+ result) } } test4() document.write("
") var test5 = function() { let result = run(35); if(result != 'BuzzWhizz') { document.write('The test 5 failed') }else { document.write('The test 5 result is : '+ result) } } test5() document.write("
") var test6 = function() { let result = run(15); if(result != 'FizzBuzz') { document.write('The test 6 failed') }else { document.write('The test 6 result is : '+ result) } } test6() document.write("
") var test7 = function() { let result = run(21); if(result != 'FizzWhizz') { document.write('The test 7 failed') }else { document.write('The test 7 result is : '+ result) } } test7() document.write("
") var test8 = function() { let result = run(105); if(result != 'FizzBuzzWhizz') { document.write('The test 8 failed') }else { document.write('The test 8 result is : '+ result) } } test8()