语句块
while (x < 10) {
x++;
}
/*
{x++;}
就是一个语句块
*/
注意:ECMA 2015之前的 ,没有块范围的变量;在ECMA 2015之后,由 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 ( ) {
case label_1:
statements_1
[break;] // 可选
/*
若该case标签,被匹配了,但其中没有break,
那么就会顺序执行下一个case标签的判断,而不会跳出switch语句;
若有break,该处case标签执行完成之后,会跳出switch语句。
*/
case label_2:
statements_2
[break;]
...
default:
statements_def
[break;]
}
/*
使用 匹配各个case标签,
匹配了就执行其中的语句;
若无匹配case标签,会执行default中的语句。
*/
异常处理语句
可以使用throw语句,抛出异常;使用try...catch语句,处理异常。
异常类型
- ECMA exceptions
- DOMException & DOMError
throw语句
/*
throw ;
*/
throw \'Error2\'; // String type
throw 42; // Number type
throw true; // Boolean type
throw {toString: function() { return \"I\'m an !\"; } };
// Create an 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 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 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 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 {
doSomethingToGetA Error();
}
}
....
try {
doSomethingErrorProne();
} catch (e) {
console.log(e.name); // logs \'Error\'
console.log(e.message); // logs \'The message\' or a error message)
}
Promises
从ECMA 2015开始, 增加用来控制延迟和异步操作流程的Promise对象
<!DOCTYPE html>
<html>
<head>
< charset=\"utf-8\">
< http-equiv=\"X-UA-Compatible\" content=\"IE=edge,chrome=1\">
< name=\"viewport\" content=\"width=device-width\">
< >Promise example</ >
< rel=\"stylesheet\" href=\"\">
<!--[if lt IE 9]>
< src=\"//html5shiv.googlecode.com/svn/trunk/html5.js\"></ >
<![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>
< >
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 HttpRequest();
request.open(\'GET\', url);
request.responseType = \'blob\';
// When the request loads, check whether it was successful
request. = 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. = 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
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.create URL(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);
});
</ >
</html>
继续阅读与本文标签相同的文章
上一篇 :
云脉斩获创客中国“大数据技术及应用”组一等奖
-
华为网络:强交互式舒适级VR体验需要540M宽带
2026-05-19栏目: 教程
-
缙云“人才·科技”峰会人才项目路演成功举行
2026-05-19栏目: 教程
-
谷歌发布Nest mini音箱:音质增强 售价49美元
2026-05-19栏目: 教程
-
微信转账还能换颜色?好友都懵了!
2026-05-19栏目: 教程
-
为何许多学生都用QQ,而步入社会后就变成了微信?理由让人泪目
2026-05-19栏目: 教程
