注释很详细,直接上代码
涉及知识点:
- 条件排序封装
- 渲染列表
题干:
我的答案
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8" /></head><body><button class="up">销量升序</button><button class="down">销量降序</button><ul></ul><script>/*** emmm,这题感觉没啥新东西,凑合看看吧*/var cups = [{type: 1,price: 100,color: "black",sales: 3000,name: "牛客logo马克杯",},{ type: 2, price: 40, color: "blue", sales: 1000, name: "无盖星空杯" },{ type: 4, price: 60, color: "green", sales: 200, name: "老式茶杯" },{ type: 3, price: 50, color: "green", sales: 600, name: "欧式印花杯" },];var ul = document.querySelector("ul");var upbtn = document.querySelector(".up");var downbtn = document.querySelector(".down");// 补全代码/*** 商品排序* @param {number} sign - 0升序,1降序* @returns {void}*/const sortList = (sign) => {cups.sort((a, b) => {if (sign == 0) return a.sales - b.sales;else return b.sales - a.sales;});};/*** 渲染列表* @param {object[]} cups - 商品列表* @returns {void}*/const showList = (cups) => {ul.innerHTML = "";cups.forEach((cup) => {let li = document.createElement("li");li.innerHTML = `${cup.name}`;ul.appendChild(li);});};//点击升序upbtn.onclick = function () {sortList(0);showList(cups);};//点击降序downbtn.onclick = function () {sortList(1);showList(cups);};</script></body>
</html>
博客更新不是很及时,需要看后面内容的可以看看我的
gitee仓库
牛客JS题Gitee仓库