for循环?好像是听说这是菜鸟一贯作风(抱头瑟瑟发抖... ...)
但是你知道几种?往下看,欢迎补充~
1、for循环,为了证明我不要当菜鸟的决心,我就直接跳过,连挥手都来不及的那种。
。。。 。。。
2、forEach循环,循环数组中每一个元素并采取操作, 没有返回值, 可以不用知道数组长度。
返回值:无
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<title>forEach方法</title>
</head>
<body>
<script type="text/javascript">
var arr = [6, 5, 4];
var total = 0;
arr.forEach(function(value, index, arr) {
console.log('当前值:' + value);
console.log('当前值对应的索引:' + index);
console.log('原数组:' + arr);
total += value
});
console.log(total);
</script>
</body>
</html>
输出:
3、map函数,遍历数组每个元素,并回调操作,需要返回值,返回值组成新的数组,原数组不变。
返回值:返回按返回值生成的新数组
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<title>map方法</title>
</head>
<body>
<script type="text/javascript">
var arr = [6, 5, 4];
var arrNew = [];
arrNew = arr.map(function(value, index, arr) {
console.log('当前值:' + value);
console.log('当前值对应的索引:' + index);
console.log('原数组:' + arr);
return value * value
});
//map返回新数组
console.log(arrNew);
</script>
</body>
</html>
输出:
4、filter函数, 过滤通过条件的元素组成一个新数组, 原数组不变
返回值:返回过滤条件生成的新数组
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<title>filter方法</title>
</head>
<body>
<script type="text/javascript">
var arr = [6, 5, 4];
var arrNew = [];
arrNew = arr.filter(function(value, index, arr) {
console.log('当前值:' + value);
console.log('当前值对应的索引:' + index);
console.log('原数组:' + arr);
return value % 2 == 0;
});
//map返回新数组
console.log(arrNew);
</script>
</body>
</html>
输出:
5、some函数,遍历数组中是否有符合条件的元素,返回Boolean值
返回值:返回Boolean值,是否含有符合条件的元素
6、every函数, 遍历数组中是否每个元素都符合条件, 返回Boolean值
返回值:返回Boolean值,是否全部符合条件的元素
7、恭喜你。魂环增加一级,可以点赞走掉了。