遍历数组练习(filter,some,foreach)

本文深入探讨了JavaScript中三种常见的数组遍历方法:filter、some和forEach。通过实例代码,详细解释了它们的工作原理、用法及应用场景,帮助开发者更好地理解和运用这些方法进行数组操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

th,
  td {
    height: 50px;
    width: 200px;
  }
<div>
    <p>按照价格查询:<input type="text">-<input type="text">
      <input type="button" value="搜索">按照商品名称查询:
      <input type="text"><input type="button" value="查询">
    </p>
  </div>
  <table style="text-align: center" border="1" cellspacing='0' cellpadding='0'>
    <thead>
      <th>id</th>
      <th>产品名称</th>
      <th>价格</th>
    </thead>
    <tbody></tbody>
  </table>
var data = [{
        name: '小米',
        id: 1,
        price: 3999
      },
      {
        name: 'oppo',
        id: 2,
        price: 999
      },
      {
        name: '荣耀',
        id: 3,
        price: 1299
      },
      {
        name: '华为',
        id: 4,
        price: 1999
      },
    ]
    var tbody = document.querySelector('tbody')
    var ipts = document.querySelectorAll('[type=text]')
    var btns = document.querySelectorAll('[type=button]')
    init(data)

    function init(data) {
      tbody.innerHTML = ''
      data.forEach((val) => {
        var tr = document.createElement('tr')
        tr.innerHTML = '<td>' + val.id + '</td><td>' + val.name + '</td><td>' + val.price + '</td>'
        tbody.appendChild(tr)
      })
    }
    btns[0].onclick = function () {
      var iptval1 = ipts[0].value.trim()
      var iptval2 = ipts[1].value.trim()
      if (iptval1 == '' && iptval2 == '') {
        return init(data)
      } else if (iptval1 == '' && iptval2 != '') {
        init(data.filter((val) => {
          return val.price <= ipts[1].value
        }))
      } else if (iptval1 != '' && iptval2 == '') {
        init(data.filter((val) => {
          return val.price >= ipts[0].value
        }))
      } else {
        init(data.filter((val) => {
          return val.price >= ipts[0].value && val.price <= ipts[1].value
        }))
      }
    }
    btns[1].onclick = function () {
      var index = 0
      if (ipts[2].value == '') {
        return init(data)
      }
      if (data.some((val, i) => {
          index = i
          return val.name == ipts[2].value
        })) {
        init([data[index]])
      } else {
        init([])
      }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值