js forEach for區別
阿新 • • 發佈:2018-09-03
view false ext 使用 viewport 區別 ble tcs col
1、循環中斷差別
具體見示例代碼:
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title >js for forEach區別 </title>
</head>
<body>
<script src="https://cdn.bootcss.com/lodash.js/4.17.10/lodash.min.js"></script>
<script type="text/javascript">
let arr = [1, 2, 3, 4]
for(let i = 0; i < arr.length; i++) {
if(arr[i] == 2) {
continue;
//break;
}
console.log(arr[i], ‘ for‘)
}
for(let i in arr) {
if(i == 2) {
break;
}
console.log(arr[i], ‘ for in‘)
}
for(let i of arr) {
if(i == 2) {
break;
}
console.log(i, ‘ for of‘)
}
arr.forEach(val => {
if(val == 2) {
//此處的return false 僅僅相當於continue
return false;
//break或者continue均不能使用 會報錯,對於map filter方法一樣會報錯
//break;
//continue
}
console.log(val, ‘ forEach‘)
})
</script>
</body>
</html>
數組的叠代方法:every、filter、forEach、map、some均不能使用break或者continue進行中斷循環。
2、數組變化時差別
(1)數組添加操作
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>js for forEach區別 </title>
</head>
<body>
<script src="https://cdn.bootcss.com/lodash.js/4.17.10/lodash.min.js"></script>
<script type="text/javascript">
let arr = [1, 2, 3, 4]
for(let i = 0; i < arr.length; i++) {
if(arr[i] == 2) {
//對於添加時,for可以遍歷新數組
arr.push(5)
}
// 輸出1 2 3 4 5
console.log(arr[i], ‘ for‘)
}
arr.forEach(val => {
if(val == 2) {
//對於添加時,forEach
arr.push(5)
}
// 輸出1 2 3 4 5
console.log(val, ‘ forEach‘)
})
</script>
</body>
</html>
(2)數組更新、刪除操作
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>js for forEach區別 </title>
</head>
<body>
<script src="https://cdn.bootcss.com/lodash.js/4.17.10/lodash.min.js"></script>
<script type="text/javascript">
let arr = [1, 2, 3, 4]
for(let i = 0; i < arr.length; i++) {
if(arr[i] == 2) {
//對於更新、刪除時,for可以遍歷新數組
arr[1] = 100
//arr.splice(i,1)
}
// 輸出1 100 3 4
console.log(arr[i], ‘ for‘)
}
arr.forEach((val, i) => {
if(val == 2) {
//對於更新、刪除時,forEach可以遍歷新數組
val = 100
//arr.splice(i,1)
}
// 輸出1 100 3 4
console.log(val, ‘ forEach‘)
})
</script>
</body>
</html>
js forEach for區別