带有多个语句的JavaScript ' if '
JavaScript `if` with multiple statements
为什么上面的代码可以工作而下面的代码不能?
这个有效:
var i=1
function next() {
document.getElementById("photo").src = "http://www.Example.com/images/" + jsArray[i];
if (i<jsArray.length-2)
i++
else
i=0
}
这个不行:
var i=1
function next() {
if (i<jsArray.length-2)
i++
document.getElementById("photo").src = "http://www.Example.com/images/" + jsArray[i];
else
i=0
document.getElementById("photo").src = "http://www.Example.com/images/" + jsArray[i];
}
如果您希望在if
或else
条件后面有多个语句,则需要将它们包装在一个块中:
function next() {
if (i<jsArray.length-2) {
i++
document.getElementById("photo").src = "http://www.Example.com/images/" + jsArray[i];
}
else {
i=0
document.getElementById("photo").src = "http://www.Example.com/images/" + jsArray[i];
}
}
注意,这在语法上是等价的——if
语句后面仍然跟着一条语句(一个块语句)。
语法给出了完整的细节:
IfStatement :
,,,,if (
表达式)
语句else
语句
,,,,if (
表达式)
语句
这表明if
语句只能后跟一条语句。
必须将条件为真时需要执行的代码块放在花括号中。
var i=1
function next() {
if (i<jsArray.length-2)
{
i++
document.getElementById("photo").src = "http://www.Example.com/images/" + jsArray[i];
}
else
{
i=0
document.getElementById("photo").src = "http://www.Example.com/images/" + jsArray[i];
}
}
你需要大括号:
function next() {
if (i<jsArray.length-2) {
i++;
document.getElementById("photo").src = "http://www.Example.com/images/" + jsArray[i];
} else {
i=0;
document.getElementById("photo").src = "http://www.Example.com/images/" + jsArray[i];
}
}
我还选择添加分号。
对于JS错误/警告,你可能会发现JSLint很有帮助:http://www.jslint.com
相关文章:
- 在PHP中使用javascript更改页面标题'if'
- gulp-if-javascript文件,但不在gulp-useref的特定目录中
- 带有多个elseif的Javascript if语句
- Javascript:If-then语句在函数中不起作用
- for循环中的javascript if语句找不到==
- Javascript Return and if/else
- Javascript nested if
- 在if语句下的html中使用javascript变量
- JavaScript if-else 速记错误
- 避免在if condition-Javascript中使用函数
- 在javascript中创建数组,而不是if.else
- 在Javascript中将一个值和字符串数组转换为if语句
- Javascript If else 只返回 TRUE 或只返回 FALSE
- 如何重写Javascript If语句以选择Classes而不是ID's的HTML格式
- 在Javascript中为if/else语句添加OR
- 重定向至If-Javascript诊断树
- if-else-if JavaScript 返回 true 并退出,无论输入如何
- 在 IF Javascript 中赋值变量
- 写一个if.JavaScript中的else语句和switch语句
- “if"javascript中的多个条件