一、在编写javascript时我们经常会遇到数字与字符串两种数据类型需要相互转换,将字符串转换成数字是我们可以直接调用函数,而如果要将数字转换成字符型都有哪些方法呢,请参见下面的示例。
示例1:将字符串转换成数字
<script>
var str1="31 days in january"
var int1=parseInt(str1)
document.write("str1的数据类型是 :"+typeof str1+"<br>")
document.write("int1的数据类型是 :"+typeof int1+"<br>")
</script>
示例2:将数字转换成字符串
<script>
var int1=256
var str1=""+int1
document.write("str1的数据类型是 :"+typeof str1+"<br>")
document.write("int1的数据类型是 :"+typeof int1+"<br>")
</script>
示例3:将数组转换为字符串
<script>
array=new Array()
array[0]="dark"
array[1]="apple"
array[2]="nebula"
array[3]="water"
str1=array.join()
str2=array.join(" ")
document.write(str1+"<br>")
document.write(str2)
</script>
二、If……else 是我们最常用的条件判断语句,其实有些时候,一个If……else语句可以有一个简单的语句来代替,也就是使用条件运算符,使用方法请参见下面的示例。
示例1:
<script language="JavaScript">
stomach="hungry";
time="5:00";
(stomach=="hungry"&&time=="5:00") ? eat = "dinner":eat="a snack";
document.write("输出结果"+eat);
</script>
三、循环是我们比较常用的流程控制语句,而我们还经常会需要在整个循环过程中进行条件判断,根据条件判断决定该循环是否需要被终止,那么终止循环有两种方式,一是终止整个循环进入下一次循环,而另外一中则是终止本次循环进入下一次循环,具方法分别参见示例1、2。
示例1:中断循环
<script>
count=1
while(count<=15){
count++
if(count==8)
break;
document.write("输出第"+count+"句"+"<br>")}
</script>
示例2:进入下次循环
<script>
count=1
while(count<=15){
count++
if(count==8)
continue;
document.write("输出第"+count+"句"+"<br>")}
</script>
四、很多情况下,我们需要定时重复执行一些操作,比如我们想实现一个时钟,就要每隔1000毫秒做一次时间增加一秒,这样的情况下,我们需要使用JavaScriopt中的定时器,具体使用方法参见示例1、2,已经设置间隔后的清除方法参见示例3。
示例1:使用JavaScript定时器
<script>
function rabbit()
{document.write("输出语句")
}
</script>
<body onload=window.setTimeout(rabbit(),5000)>
示例2:设置定期间隔
<script>
window.setInterval("document.form1.text2.value=document.form1.text1.value",3000)
</script>
<form name=form1>
<input type=text name=text1><br>
<input type=text name=text2><br>
</form>
示例3:清除超时和间隔
<script>
stop=window.setInterval("document.form1.text2.value=document.form1.text1.value",300)
</script>
<form name=form1>
<input type=text name=text1><br>
<input type=text name=text2><br>
<input type=button name=button1 value=" 清除超时和间隔" onclick=clearInterval(stop)>
</form>