概述
语句块
while (x < 10) {
x++;
}
/*
{x++;}
就是一个语句块
*/
注意:ECMAScript2015之前的JavaScript,没有块范围的变量;在ECMAScript2015之后,由 let const 定义的变量才是块范围。
var x = 1;
{
var x = 2;
}
console.log(x); // outputs 2
/*
花括号中定义的 var x
同花括号上方定义的 var x
处于相同的块范围中,可以尝试修改 var 为 let 试一试
*/
let x = 1;
{
let x = 2;
}
console.log(x);
/*
会出现异常
因为,名称为 x 的变量,在上方已经定义了,
不能重复定义,使用相同名称的变量。
*/
条件语句
if ... else 语句
if (condition) {
statement_1; // 条件判断为真,执行
} else {
statement_2; // 条件判断为假,执行
}
if (condition_1) {
statement_1;
} else if (condition_2) {
statement_2;
} else if (condition_n) {
statement_n;
} else {
statement_last;
}
if (condition) {
statement_1_runs_if_condition_is_true;
statement_2_runs_if_condition_is_true;
} else {
statement_3_runs_if_condition_is_false;
statement_4_runs_if_condition_is_false;
}
评估为假值的值:
- false
- undefined
- null
- 0
- 空白字符串 ("")
- 除此以为的值,在条件判断中,会被评估为真
var b = new Boolean(false);
if (b) // 条件结果为:真
if (b == true) // 条件结果为:假
switch 语句
switch (expression) {
case label_1:
statements_1
[break;] // 可选
/*
若该case标签,被匹配了,但其中没有break,
那么就会顺序执行下一个case标签的判断,而不会跳出switch语句;
若有break,该处case标签执行完成之后,会跳出switch语句。
*/
case label_2:
statements_2
[break;]
...
default:
statements_def
[break;]
}
/*
使用expression匹配各个case标签,
匹配了就执行其中的语句;
若无匹配case标签,会执行default中的语句。
*/
异常处理语句
可以使用throw语句,抛出异常;使用try...catch语句,处理异常。
异常类型
- ECMAScript exceptions
- DOMException & DOMError
throw语句
/*
throw expression;
*/
throw 'Error2'; // String type
throw 42; // Number type
throw true; // Boolean type
throw {toString: function() { return "I'm an object!"; } };
// Create an object type UserException
function UserException(message) {
this.message = message;
this.name = 'UserException';
}
// Make the exception convert to a pretty string when used as a string
// (e.g. by the error console)
UserException.prototype.toString = function() {
return this.name + ': "' + this.message + '"';
}
// Create an instance of the object type and throw it
throw new UserException('Value too high');
try...catch语句
function getMonthName(mo) {
mo = mo - 1; // Adjust month number for array index (1 = Jan, 12 = Dec)
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul',
'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
if (months[mo]) {
return months[mo];
} else {
throw 'InvalidMonthNo'; //throw keyword is used here
}
}
try { // statements to try
monthName = getMonthName(myMonth); // function could throw exception
}
catch (e) {
// 捕获由try语句块,抛出的异常
monthName = 'unknown';
logMyErrors(e); // pass exception object to error handler -> your own function
}
catch块
catch块,可以处理由其对应的try块抛出的所有的异常
try {
throw 'myException'; // generates an exception
}
catch (e) {
// statements to handle any exceptions
logMyErrors(e); // pass exception object to error handler
}
finally块
openMyFile();
try {
writeMyFile(theData); //This may throw an error
} catch(e) {
handleError(e); // If we got an error we handle it
} finally {
closeMyFile(); // always close the resource
/*
finally块
无论是否有异常发生,该块都会被执行
*/
}
function f() {
try {
console.log(0);
throw 'bogus';
} catch(e) {
console.log(1);
return true; // 该return会被挂起,直到finally块完成
console.log(2); // 不可达
} finally {
console.log(3);
return false; // 覆盖catch中的return语句
console.log(4); // 不可达
}
// "return false" is executed now
console.log(5); // 不可达,在try...catch...finally实体中的finally块已经返回
}
f(); // console 0, 1, 3; returns false
function f() {
try {
throw 'bogus';
} catch(e) {
console.log('caught inner "bogus"');
throw e; // 该语句被挂起,直到finally执行完成
} finally {
return false; // 覆盖上方的throw语句,返回false值
}
// "return false" is executed now
}
try {
f();
} catch(e) {
/*
不可达
由于f()语句中catch块中的throw语句
被其finally语句中的return语句覆盖,方法直接返回执行结果了
*/
console.log('caught outer "bogus"');
}
// OUTPUT
// caught inner "bogus"
利用Error对象
function doSomethingErrorProne() {
if (ourCodeMakesAMistake()) {
throw (new Error('The message'));
} else {
doSomethingToGetAJavascriptError();
}
}
....
try {
doSomethingErrorProne();
} catch (e) {
console.log(e.name); // logs 'Error'
console.log(e.message); // logs 'The message' or a JavaScript error message)
}
Promises
从ECMAScript2015开始,JavaScript增加用来控制延迟和异步操作流程的Promise对象
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width">
<title>Promise example</title>
<link rel="stylesheet" href="">
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<h1>Promise example</h1>
<p>Darth Vader image by <a href="https://www.flickr.com/photos/digital_stability/">Shawn Taylor</a>, published
under a <a href="https://creativecommons.org/licenses/by-nc-nd/2.0/">Attribution-NonCommercial-NoDerivs 2.0
Generic</a> license.</p>
</body>
<script>
function imgLoad(url) {
// Create new promise with the Promise() constructor;
// This has as its argument a function
// with two parameters, resolve and reject
return new Promise(function (resolve, reject) {
// Standard XHR to load an image
var request = new XMLHttpRequest();
request.open('GET', url);
request.responseType = 'blob';
// When the request loads, check whether it was successful
request.onload = function () {
if (request.status === 200) {
// If successful, resolve the promise by passing back the request response
resolve(request.response);
} else {
// If it fails, reject the promise with a error message
reject(Error('Image didn't load successfully; error code:' + request.statusText));
}
};
request.onerror = function () {
// Also deal with the case when the entire request fails to begin with
// This is probably a network error, so reject the promise with an appropriate message
reject(Error('There was a network error.'));
};
// Send the request
request.send();
});
}
// Get a reference to the body element, and create a new image object
var body = document.querySelector('body');
var myImage = new Image();
// Call the function with the URL we want to load, but then chain the
// promise then() method on to the end of it. This contains two callbacks
imgLoad('myLittleVader.jpg').then(function (response) {
// The first runs when the promise resolves, with the request.response
// specified within the resolve() method.
var imageURL = window.URL.createObjectURL(response);
myImage.src = imageURL;
body.appendChild(myImage);
// The second runs when the promise
// is rejected, and logs the Error specified with the reject() method.
}, function (Error) {
console.log(Error);
});
</script>
</html>
最后
以上就是安详小懒虫为你收集整理的JavaScript - 流程控制和错误处理的全部内容,希望文章能够帮你解决JavaScript - 流程控制和错误处理所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复