JavaScript 条件语句
- if语句
有些代码块只能在一定条件下运行,通过if、if else、else代码块,可以让你的代码按条件执行。
// 控制流var foo = true;var bar = false;if ( bar ) {// 这里的代码将无法运行。console.log( "hello!" );}if ( bar ) {// 这里的代码将无法运行。} else {if ( foo ) {// 这里的代码是可以运行的。} else {// 当foo和bar都为false的时候这里的代码才能运行}} |
- 真与假
为了if语句的执行成功,重要的是了解条件是真还是假。
// 真"0";"any string";[]; // 一个空数组{}; // 一个空对象1; // 任意非0数。// 假""; // 空字符串NaN; null;undefined;0; // 数字0 |
- 三元运算条件赋值
有时候一个变量的设置需要由某个条件决定,这时可以使用if语句来实现,但是使用三元运算会更加的方便,三元运算时检测条件,如果条件为真返回特定值,如果条件为假则返回另一个值。
// 如果bar为真foo就等于1,否则foo就等于0:var foo = bar ? 1 : 0; |
- Switch语句
除了if语句外还有switch语句可以进行条件控制,根据条件的值决定执行相应的代码块。
switch ( foo ) {case "bar":alert( "the value was bar -- yay!" );break;case "baz":alert( "boo baz :(" );break;default:alert( "everything else is just ok" );} |
另外可以通过创建对象的形式实现switch语句的功能。
var stuffToDo = {"bar": function() {alert( "the value was bar -- yay!" );},"baz": function() {alert( "boo baz :(" );},"default": function() {alert( "everything else is just ok" );}};if ( stuffToDo[ foo ] ) {stuffToDo[ foo ]();} else {stuffToDo[ "default" ]();} |

浙公网安备 33010602011771号