forEach,filter,some,trim四种方法的使用以及应用场景
1.forEach
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>14_forEach方法</title>
</head>
<body>
<script>
// forEach 迭代(遍历)数组
var arr = [1,2,3]
var sum = 0
//三个参数,用时可以根据自身需要设置形参
arr.forEach(function(value,index,array) {
console.log('每个数组元素'+value);
console.log('每个数组元素的索引号'+index);
console.log('数组本身'+array);
sum+=value
});
console.log(sum);
</script>
</body>
</html>
2.filter方法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>15_filter筛选数组</title>
</head>
<body>
<script>
var arr = [12,66,4,88,3,7]
var newArr = arr.filter(function(value,index){
// return value>=20
return value % 2 == 0//条件
})//会返回符合条件的新数组
console.log(newArr);
</script>
</body>
</html>
3.some方法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>16_some方法</title>
</head>
<body>
<script>
// some 查找数组中是否有满足条件的元素 找到了直接就返回true 不然就返回false
var arr = [10,30,4]
var flag = arr.some(function(value){
return value<3
})
console.log(flag);
</script>
</body>
</html>
4.trim方法(也可适用于在检测密码时不能输入空格)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>17_trim方法去除字符串两侧空格</title>
</head>
<body>
<input type="text"> <button>点击</button>
<div></div>
<script>
//trim方法去除字符串两侧的空格
var str = ' andy '
console.log(str);
var str1 = str.trim();
console.log(str1);
var input = document.querySelector('input')
var btn = document.querySelector('button')
var div = document.querySelector('div')
btn.onclick = function(){
var str = input.value.trim();
if(str == ''){
alert('请输入内容')
}else{
console.log(str);
console.log(str.length);
div.innerHTML = str
}
}
</script>
</body>
</html>