You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按价格对水果沙拉购物清单的提示输出结果排序?

水果沙拉购物清单按价格排序实现方案

我正在开发一个水果沙拉购物清单小项目,支持用户添加食材并设置价格。目前已实现通过提示框展示所有添加的食材及价格,但需要将内容按价格从低到高排序展示,查找相关资料未获有效信息,寻求技术帮助。

原始代码

var count = 0;
var fruitSaladItems = [];
var ingredient=true;

 while (ingredient && count<22) {
      count++
  
      ingredient= prompt("Enter the fruit salad ingredients");
      if(ingredient){
        var price=prompt("Enter the price");
             fruitSaladItems.push(ingredient+" €"+price);
        
      }
}

alert(fruitSaladItems.join(','));

修改后的代码(未完成排序)

var count = 0;
var fruitSaladItems = [];
var ingredient=true;

 while (ingredient && count<22) {
      count++
  
     ingredient = prompt("Enter the fruit salad ingredients");
     if (ingredient) {
      var price = parseFloat(prompt("Enter the price"));
      fruitSaladItems.push({ ingredient, price });
      
      }
}

alert(fruitSaladItems.join(','));

完整实现排序的代码

你把食材和价格存为对象的思路是对的,这样才能基于数值类型的价格进行排序。以下是补全排序逻辑后的完整代码:

var count = 0;
var fruitSaladItems = [];
var ingredient = true;

while (ingredient && count < 22) {
  count++
  
  ingredient = prompt("请输入水果沙拉食材");
  if (ingredient) {
    var priceInput = prompt("请输入价格");
    var price = parseFloat(priceInput);
    // 校验价格是否为有效数字,避免无效输入干扰排序
    if (!isNaN(price)) {
      fruitSaladItems.push({ ingredient, price });
    } else {
      alert("请输入有效的数字价格");
      count--; // 无效输入不消耗计数,允许重新输入
    }
  }
}

// 按价格从低到高排序
fruitSaladItems.sort((a, b) => a.price - b.price);

// 将排序后的对象数组转换为可读字符串
var displayContent = fruitSaladItems.map(item => `${item.ingredient} €${item.price}`).join(', ');

alert(displayContent);

关键说明

  • 排序逻辑:使用数组的sort()方法,传入比较函数(a, b) => a.price - b.price,通过两个对象的价格差值实现升序排序;如果需要降序,改为b.price - a.price即可。
  • 格式转换:用map()方法遍历排序后的数组,把每个对象转换成用户能看懂的"食材 €价格"格式,再用join(', ')拼接成逗号分隔的文本。
  • 输入校验:增加了价格有效性判断,避免用户输入非数字内容导致排序异常,同时回退计数让用户重新输入该食材的价格。

内容的提问来源于stack exchange,提问作者Micos15

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 02:54:23