Mik*_*key -1 javascript if-statement
为什么顶部代码有效而底部代码无效?
这个工作:
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
}
Run Code Online (Sandbox Code Playgroud)
这个不起作用:
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];
}
Run Code Online (Sandbox Code Playgroud)
如果你想要一个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];
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,语法上这是等价的 - 该if语句后面仍然跟着一个语句(一个块语句).
语法提供了完整的细节:
IfStatement:
if (表达式)语句else语句
if (表达式)语句
这表明if语句后面只能跟一个语句.