程序功能:利用JS编程,创建一个函数,清除等于0的元素
) q7 t$ _5 [* b) B% p1 d7 [程序要求:将业务逻辑封装成函数,设计一组数据进行测试,显示测试结果
6 X- ?7 Y7 u9 Z4 e" X4 x7 J程序原理:利用filter方法对数组进行过滤,通过检查指定数组中符合条件的所有元素(注意:filter()不会对空数组进行检测、不会改变原始数组)
, t4 J8 _, z9 _1 c8 z" w一、语法:9 n* N- J, p5 s6 Z* E! s# ]
Array.filter(function(currentValue, indedx, arr), thisValue)
: e8 S5 g# F4 f 其中,函数 function 为必须,数组中的每个元素都会执行这个函数。且如果返回值为 true,则该元素被保留;函数的第一个参数 currentValue 也为必须,代表当前元素的值。2 P _2 K! T, h+ w( b/ x& v
二、用法:8 [0 r. Y3 t7 _
返回数组nums中所有大于5的元素。
4 ?8 L* K$ R4 mlet nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let res = nums.filter((num) => {
return num > 5;
});
console.log(res); //结果 [6, 7, 8, 9, 10] 三、按要求的完整实例:
0 {3 Y. K, P0 F2 a9 a<!DOCTYPE Html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>删除0</title>
</head>
<body>
<div class="main">
输入数组:<input type="text" class="arr" value="0, 0, 0, 1, 20, 0, 0, 3, 4, 5, 0">
<button class="del">处理</button> <br>处理结果:
<input class="result" disabled></h1>
</div>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script>
function clearNumber(arr) {
return arr.filter(item => item != 0)
}
$('.del').click(function name() {
var array = [];
var arr = $('.arr').val().split(',');
for (var i = 0; i < arr.length; i++) {
array.push(parseFloat(arr[i]));
}
$('.result').val(clearNumber(array))
})
</script>
</body>
</html>
7 X8 w& |0 x3 ]1 n- f: T6 N% s8 I/ n+ Z0 A9 |
|