Js运算符
“=”——用于赋值;“+”——用于加值
“*”——乘;“/”——除;“%”——求余数(保留整数)
“++”——累加;“--”——递减
a+=b等价于a=a+b;a-=b等价于a=a-b;其他类似
用于字符串的+运算符
t1=“My”;t2=“SQL”;
t3=t1+t2; //t3的值为MySQL
注:Js可以把数字和字符串相加,但结果将成为字符串。
JavaScript比较和逻辑运算符
用于测试true或false
== | === | != | > | < | >= | <= |
等于 | 全等(值和类型) | 不等于 | 大于 | 小于 | 大于或等于 | 小于或等于 |
使用:if(iq>150)document.write("smart");
&& | || | ! |
and | or | not |
使用:
variablename=(condition)?value1:value2
condition为true;variablename=value1,否则=value2
JavaScript的If语句
用来基于不同条件来执行不同的动作。
- if语句 当条件为true,执行;
- if...else 当条件为true,执行if下的代码,否则执行else下的代码;
- if...else if...else语句 多重判断执行其中判断为true的一个
- switch语句 选择其下一个分支块的代码执行
例如:
<!DOCTYPE html>
<html>
<body>
<p>请点击这个羊驼,你会得到你想要的祝福。</p>
<button onclick="dog()">羊驼</button>
<p id="maybe"></p>
<script>
function dog()
{
var a="";
var time=new Date().getHours();
if(time>18&&time<23)
{
a="Go Home";
}
else if(time>8&&time<=18)
{
a="Go Lib";
}
else
{
a="Go to bed";
}
document.getElementById("maybe").innerHTML=a;
}
</script>
</body>
</html>
JavaScript循环
- for - 循环代码块一定的次数
- for/in - 循环遍历对象的属性
- while - 当指定的条件为 true 时循环指定的代码块
- do/while - 同样当指定的条件为 true 时循环指定的代码块
continue结束本次循环;break终止循环(跳出);