filter和forEach函数,遇见return不会终止迭代,而是全部遍历一遍。而some遇见return会终止迭代。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>查询商品案例</title>
<style>
* {
padding: 0;
margin: 0;
}
.banner {
height: 80px;
width: 100%;
text-align: center;
line-height: 80px;
}
.main {
margin: 0 auto;
width: 600px;
}
table {
border: 1px solid black;
border-collapse: collapse;
}
th,
td {
text-align: center;
border: 1px solid black;
}
input {
width: 100px;
}
</style>
</head>
<body>
<div class="banner">
根据价格查询:<input type="number" id="price1" >-<input type="number" id="price2"> <button class="search-price">搜索</button>按照商品名称查询:<input type="text" name="" id="namee"><button class="search-name">查询</button>
</div>
<div class="main">
<table>
<thead>
<tr>
<th style="width: 100px;">id</th>
<th style="width: 200px">产品名称</th>
<th style="width: 200px;">价格</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<script>
var data = [{
id:1,
param: '小米',
price:3999
},{
id:2,
param: 'oppo',
price:999
},{
id:3,
param: '荣耀',
price:4999
},{
id:4,
param: '华为',
price:5999
}]
// 加载数据:
var tbody = document.querySelector('tbody');
// 渲染数据。
setDate(data);
function setDate(mydata) {
// 先清空原来的数据。
tbody.innerHTML = '';
mydata.forEach(function(value){
var tr = document.createElement('tr');
tr.innerHTML = '<td>'+value.id+'</td><td>'+value.param+'</td><td>'+value.price+'</td>';
tbody.appendChild(tr);
});
};
var searchPrice = document.querySelector('.search-price');
var searchName = document.querySelector('.search-name');
var price1 = document.querySelector('#price1');
var price2 = document.querySelector('#price2');
var namee = document.querySelector('#namee');
searchPrice.addEventListener('click', function() {
var p1 = price1.value;
var p2 = price2.value;
var newDate = data.filter(function(value) {
return value.price >= p1 && value.price <= p2;
})
setDate(newDate);
});
searchName.addEventListener('click', function() {
var name1 = namee.value;
var target = [];
data.some(function(value) {
if(value.param == name1) {
target.push(value);
return true;
}
})
setDate(target);
});
</script>
</body>
</html>