大家好,这段代码实现这样的功能:
1、用户输入全是小写字母的字符串,不支持空格和标点符号;
2、程序将字符串中的每个字母,按字母表顺序,向后移动5位,并输出新字符串;
<script type="text/javascript">
var str=prompt("请输入要加密的字符串:").split("");
var newStr=[];
var alphabet=["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"];
for(var n=0; n<=str.length; n++)
for(var i=0; i<=25;i++)
if(str[n]==alphabet[i])
if(i+5<=25)
newStr[n]=alphabet[i+5];
else
newStr[n]=alphabet[i+5-26];
alert("加密后的新字符串是:"+newStr.join(""))
</script>
上面代码可以正常运行,考虑到下一步想让程序区分大小写字母,并支持空格和标点符号,因此想用
switch(str[n]){
case str[n]==alphabet[i]&&i+5<=25:
newStr[n]=alphabet[i+5];
break;
case str[n]==alphabet[i]&&i+5>25:
newStr[n]=alphabet[i+5-26];
}
这段代码替换原代码中if判断,思路是:
1、在switch(str[n])语句中,程序先计算str[n]的值;
2、比对str[n]的值符合哪一个case中的条件,然后决定程序的走向
如果上面switch(str[n])语句能正常运行,接下来程序就可以继续扩展,再增加一个大写的判断case,再增加一个空格及标点符号的判断case
这样,这个javascript编写字符串加密程序的1.0版本就可以正式出炉了,后续会改善用户界面、由用户指定加密步长等;
但现在恳请列位老师指点,为何用switch(str[n])替代if语句,程序出错?出错代码如下:
<script type="text/javascript">
var str=prompt("请输入要加密的字符串:").split("");
var newStr=[];
var alphabet=["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"];
for(var n=0; n<=str.length; n++)
for(var i=0; i<=25;i++)
switch(str[n]){
case str[n]==alphabet[i]&&i+5<=25:
newStr[n]=alphabet[i+5];
break;
case str[n]==alphabet[i]&&i+5>25:
newStr[n]=alphabet[i+5-26];
}
alert("加密后的新字符串是:"+newStr.join(""));
</script>
补充说明,一本封皮画犀牛的书中提到,javascript中的switch有别于其他语言,因此case后面最好是常量,但没有说不可以是表达式,难道说case真的不能完成计算后面表达式的值,在与switch()中参数比对?