程序功能:利用JS编程,创建一个函数,清除等于0的元素$ _# J6 ?: ]' F' S0 o
程序要求:将业务逻辑封装成函数,设计一组数据进行测试,显示测试结果
! d# u% O& a/ E( V3 }" P程序原理:利用filter方法对数组进行过滤,通过检查指定数组中符合条件的所有元素(注意:filter()不会对空数组进行检测、不会改变原始数组)0 Q" B# }, r) h) h5 D& T
一、语法:, i2 T* f* d" @
Array.filter(function(currentValue, indedx, arr), thisValue)+ _' T1 Y" F6 f* S5 Q) V8 o/ ` K
其中,函数 function 为必须,数组中的每个元素都会执行这个函数。且如果返回值为 true,则该元素被保留;函数的第一个参数 currentValue 也为必须,代表当前元素的值。 n4 Q6 n# v b0 P: Q$ Z$ V
二、用法:
; A' ~; l& U& I) k2 x6 ~' _; G1 [1 r 返回数组nums中所有大于5的元素。) {6 F& }( r7 y% k. |. M; \+ K
let 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] 三、按要求的完整实例:
2 E$ d4 i4 ?# M: i! b0 G<!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> 4 y( M# R6 E ^% V+ ~
, x# Y6 K3 L" o% h s& P |