思路:对数组使用filter方法进行过滤得到满足要求的数据,再对这些数据进行渲染即可。
<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'); function render(arr) { let str="" arr.forEach(item=>{ str+=`<li>${item.name}</li>` }) ul.innerHTML=str } select.onchange=function(){ switch(this.value) { case "1": render(cups.filter(item=>item.sales<100)) break; case "2": render(cups.filter(item=>item.sales>=100 && item.sales<=500)) break; case "3": render(cups.filter(item=>item.sales>500)) break; } } </script>
总结:filter方法不改变原数组,而是返回新数组;注意,下拉框的值value是字符串类型喔!