作为工具人的我,昨晚有人问我用js怎么删除一个列表中等于0的元素
一开始我想的是用循环,后来百度发现有个东西叫做filter
<!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>
输入数组:
处理结果:
评论 (0)