JavaScript中按数值重排数组并实现排序后调用show_product_block的问题
问题解决:产品列表按规则排序后展示
需求:display_data 函数需根据下拉框选中值(default/price_low/price_high/most_qty),按对应规则排序产品后调用 show_product_block 展示。目前卡在按数量(most_qty)排序的实现上。
原代码
var item =[]; function display_data(sort_value){ var my_data = get_data(); var item_price; if (my_data != null) { for (i = 0; i < my_data.length; i++) { var item_name = my_data[i].name; var item_qty = my_data[i].qty; var item_price = get_price(my_data[i].innder_id); item[i] = item_name +'-'+ item_qty +'-'+ item_price; show_product_block(item_name, item_qty,item_price); } } }
修改后未完成代码
var item =[]; function display_data(sort_value){ var my_data = get_data(); var item_price; if (my_data != null) { for (i = 0; i < my_data.length; i++) { var item_name = my_data[i].name; var item_qty = my_data[i].qty; var item_price = get_price(my_data[i].innder_id); item[i] = item_name +'-'+ item_qty +'-'+ item_price; if (sort_value == 'default') { show_product_block(item_name, item_qty,item_price); } } if (sort_value == 'most_qty'){ // 需要从item数组中按item_qty获取产品,然后在循环中调用show_product_block } } }
完整解决方案代码
// 改用对象数组存储产品数据,方便排序和取值 var productList = []; function display_data(sort_value) { var my_data = get_data(); if (!my_data) return; // 整理所有产品为结构化对象 productList = my_data.map(item => { const item_price = get_price(item.innder_id); return { name: item.name, qty: parseInt(item.qty), // 转为数字避免排序异常 price: parseFloat(item_price) // 价格转数字保证排序准确性 }; }); // 根据选中值执行对应排序逻辑 switch(sort_value) { case 'price_low': // 价格从低到高排序 productList.sort((a, b) => a.price - b.price); break; case 'price_high': // 价格从高到低排序 productList.sort((a, b) => b.price - a.price); break; case 'most_qty': // 数量从多到少排序 productList.sort((a, b) => b.qty - a.qty); break; case 'default': default: // 默认保持原数据顺序 break; } // 统一循环调用展示函数 productList.forEach(product => { show_product_block(product.name, product.qty, product.price); }); }
关键说明
- 放弃原有的字符串拼接数组,改用对象数组存储产品数据,直接通过属性获取数量、价格,避免拆分字符串的麻烦和错误。
- 排序前将
qty和price转为数字类型,防止字符串排序出现10小于2的异常情况。 - 用
switch集中处理所有排序规则,逻辑清晰,后续新增排序条件时扩展更方便。 - 最后统一循环调用展示函数,减少代码冗余,避免重复编写循环逻辑。
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

