1,前言
有時(shí)項(xiàng)目中處理數(shù)據(jù)的時(shí)候赃绊,會(huì)存在數(shù)據(jù)有誤既峡,或者為空...等等問題而報(bào)錯(cuò),由于javaScript
是單線程碧查,代碼是自上而下放到執(zhí)行棧中執(zhí)行运敢,如果某一段報(bào)錯(cuò)了,后面的代碼全都不會(huì)執(zhí)行忠售。為了避免這種情況發(fā)生传惠,我們的try
和catch
就派上用場(chǎng)了。
2档痪,語法
完整語法
try {
tryCode - 嘗試執(zhí)行的代碼塊
}
catch(error) {
catchCode - 捕獲錯(cuò)誤的代碼塊
}
finally {
finallyCode - 無論 try / catch 結(jié)果如何都會(huì)執(zhí)行的代碼塊
}
一般我們只需要用到try
和catch
涉枫,下面是幾個(gè)例子。
demo數(shù)據(jù)(下面的例子都是用這個(gè)數(shù)據(jù))
let obj = [
{
id:'001',
title:'沙漠中怎么會(huì)有泥鰍',
array:[
{
age:18
}
]
},
{
id:'002',
title:'話說完飛過一只海鷗',
array:[
{
age:17
}
]
},
{
id:'003',
title:'大峽谷的風(fēng)呼嘯而過',
array:[
{
age:21
}
]
}
]
2.1腐螟,基本使用方法
在這里我們沒有定義過param變量愿汰,通過console.log打印時(shí),javaScript會(huì)拋出一個(gè)錯(cuò)誤乐纸。
try{
console.log(param)
}
catch(error){
console.error(error)
};
console.log("如果看見了這段話說明代碼沒有被報(bào)錯(cuò)所阻塞");
控制臺(tái)
2.2衬廷,自定義報(bào)錯(cuò)信息
配合throw new Error
try{
obj.forEach(item => {
if(item.id === '002'){
throw new Error('id不能等于002');
}
});
}
catch(error){
console.error(error)
};
console.log("如果看見了這段話說明代碼沒有被報(bào)錯(cuò)所阻塞");
控制臺(tái)
3,跳出forEach循環(huán)
forEach
不能使用break
和continue
這兩個(gè)關(guān)鍵字汽绢,本身無法跳出循環(huán)吗跋,也不能像普通for
循環(huán)一樣使用return
跳出,必須遍歷所有的數(shù)據(jù)才能結(jié)束宁昭。
3.1跌宛,跳出forEach
try{
obj.forEach(item => {
console.log(`當(dāng)前id:${item.id}`)
if(item.id === '002'){
throw new Error('id等于002,跳出循環(huán)');
}
});
}
catch(error){
console.error(error)
};
console.log("如果看見了這段話說明代碼沒有被報(bào)錯(cuò)所阻塞");
控制臺(tái)
3.2积仗,跳出雙層forEach
跳出了第二層循環(huán)疆拘,第一層循環(huán)繼續(xù)執(zhí)行;
try{
obj.forEach(item => {
console.log(`第一層forEach循環(huán):${item.id}`);
try{
item.array.forEach(val => {
if(val.age < 18){
throw new Error('年齡不能小于18歲');
}
})
}catch(error){
console.error(error)
}
})
}catch(error){
console.log(error)
};
console.log("如果看見了這段話說明代碼沒有被報(bào)錯(cuò)所阻塞");
控制臺(tái)
如果看了覺得有幫助的寂曹,我是@鵬多多11997110103哎迄,歡迎 點(diǎn)贊 關(guān)注 評(píng)論;
END
往期文章
- 微信小程序自定義Tabbar隆圆,附詳細(xì)源碼
- 細(xì)數(shù)JS中實(shí)用且強(qiáng)大的操作符&運(yùn)算符
- 微信小程序request請(qǐng)求的封裝
- 微信小程序API交互的自定義封裝
個(gè)人主頁