题解 | #数组过滤#
数组过滤
https://www.nowcoder.com/practice/46d607f9bf64458daa8798339a7336d0
我想从封装的角度完成这道题,只需给一个范围值 筛选即可。有没有更好的方法。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> </head> <body> <select name="" id=""> <option value="0">请选择销量范围</option> <option value="1"><100</option> <option value="2">100~500</option> <option value="3">>500</option> </select> <ul> <li>牛客logo马克杯</li> <li>无盖星空杯</li> <li>老式茶杯</li> <li>欧式印花杯</li> </ul> <script> var cups = [ { type: 1, price: 100, color: 'black', sales: 60, name: '牛客logo马克杯' }, { type: 2, price: 40, color: 'blue', sales: 100, name: '无盖星空杯' }, { type: 4, price: 60, color: 'green', sales: 200, name: '老式茶杯' }, { type: 3, price: 50, color: 'green', sales: 600, name: '欧式印花杯' } ] var select = document.querySelector('select'); var ul = document.querySelector('ul'); select.onchange = (e) => { const index = select.value const currentCup = cups let newCups = [] switch(index) { case '1': newCups = filterCup(0, 100) break case '2': newCups = filterCup(100, 500, true) break case '3': newCups = filterCup(500, '') break default: newCups = cups } // 渲染 let s = `` for (const item of newCups) { s += `<li>${item.name}</li>` } ul.innerHTML = s } function filterCup(min, max, contain) { // contain是否个范围值 包含自身 if (contain) { min -- max ++ } return cups.filter(c => max ? (c.sales > min && c.sales < max) : c.sales > min) } </script> </body> </html>