第十八天:请勿重复添加对象到购物车
<h5>1. 需求添加对象到购物车</h5>
<h5>2. 不要重复添加</h5>
<h5>3. 添加之后排序</h5>
<pre><code class="language-javascript">// 上面的输入框为对象
let vouchers =
{
voucher : 2
}
//下面显示的
let voucherList = [
{
voucher : 1
},
{
voucher : 3
}
]
//需求添加至购物车形式
let newObj = [] ;
for(let i = 0 ; i < voucherList.length ; i++){
if(vouchers.voucher == voucherList[i].voucher){
newObj.push(i);
}
}
if(newObj.length == 0){
voucherList.push(vouchers)
}else{
console.log('不要重复加入!')
}
console.log(voucherList)
//js sort方法根据数组中对象的某一个属性值进行排序
let voucherLists = [
{
voucher : 1
},
{
voucher : 3
},
{
voucher : 2
}
]
function compare(property){
return function(a,b){
var value1 = a[property];
var value2 = b[property];
return value1 - value2;
}
}
let a = voucherLists.sort(compare('voucher'));
console.log(a)
//下面是打印出来的结果
let voucherLists = [
{
voucher : 1
},
{
voucher :2
},
{
voucher : 3
}
]
</code></pre>
<h4>2.数组对象按照某一个值做升序或降序</h4>
<pre><code class="language-javascript">/**数组根据数组对象中的某个属性值进行排序的方法
* 使用例子:newArray.sort(sortBy('number',false)) //表示根据number属性降序排列;若第二个参数不传递,默认表示升序排序
* @param attr 排序的属性 如number属性
* @param rev true表示升序排列,false降序排序
* */
let voucherLists = [
{
voucher : 1
},
{
voucher : 3
},
{
voucher : 2
}
]
function sortBy(attr,rev){
//第二个参数没有传递 默认升序排列
//if(rev == undefined){
// rev = 1;
//}else{
// rev = (rev) ? 1 : -1;
//}
rev = (rev) ? 1 : -1
return function(a,b){
a = a[attr];
b = b[attr];
if(a < b){
return rev * -1;
}
if(a > b){
return rev * 1;
}
return 0;
}
}
let a = voucherLists.sort(sortBy('voucher',false)); //第二个参数true升序 、false降序
console.log(a) //得到数组对象的降序
</code></pre>
<p>源文链接:<a href="https://www.cnblogs.com/yuwenjing0727/p/6856991.html">https://www.cnblogs.com/yuwenjing0727/p/6856991.html</a></p>