js out of the loop (break, try catch, return)

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. (Reproduced please indicate the source) https://blog.csdn.net/zhangjing0320/article/details/85049574

A, for loop (or for in loop)

  1. break
  2. try catch (any are out of the loop by loop may try catch)

return will be reported syntax error, so this will not do.

var arr = ['a', 'b', 'c'];
// break
for (var key in arr) {
    console.log(key);
	if(arr[key] === 'a') {
		break;
	}
}
// 0

// try catch
try {
	for (var key in arr) {
		console.log(key);
		if(arr[key] === 'a') {
			throw new Error('跳出循环');
		}
	}
} catch(err) {
	console.log(err); 
}
// 0  Error: 跳出循环

// return 
for (var key in arr) {
	console.log(key)
	if(arr[key] === 'a') {
		return false;
	}
}
// Uncaught SyntaxError: Illegal return statement

Two, forEach, map, filter cycle

  1. try catch

will not return an error, but it will not terminate the loop. break will report a syntax error.

var arr = ['a', 'b', 'c'];
// try catch				
try {
	arr.forEach(item => {
		console.log(item);
		if (item === 'a') {
			throw new Error('aaaaaaaaaaa');
		}
	});
} catch(err) {
	console.log(err); // 
}
// 0 Error: aaaaaaaaaaa

// return 
arr.forEach(item => {
	if (item === 'a') {
		return false;
	}
	console.log(item);
});
// b c

// break
arr.forEach(item => {
	console.log(item);
	if (item === 'a') {
		break; 
	}
});
// Uncaught SyntaxError: Illegal break statement

Three, every, some cycling

  1. Every : false return out of the loop, Come : return to true out of the loop
  2. try catch

every, some grammatical errors with break newspaper circulation

Guess you like

Origin blog.csdn.net/zhangjing0320/article/details/85049574