QQ登录

只需要一步,快速开始

APP扫码登录

只需要一步,快速开始

查看: 4054|回复: 0

[HTML/CSS/JS] JavaScript删除列表中指定元素(过滤指定元素)

[复制链接]

等级头衔

积分成就    金币 : 2861
   泡泡 : 1516
   精华 : 6
   在线时间 : 1322 小时
   最后登录 : 2025-10-13

丰功伟绩

优秀达人突出贡献荣誉管理论坛元老活跃会员

联系方式
发表于 2020-9-8 12:30:15 | 显示全部楼层 |阅读模式
程序功能:利用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 m
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]
三、按要求的完整实例:
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 |
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|手机版|小黑屋|paopaomj.COM ( 渝ICP备18007172号|渝公网安备50010502503914号 )

GMT+8, 2025-11-24 23:23

Powered by paopaomj X3.5 © 2016-2025 sitemap

快速回复 返回顶部 返回列表