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

Node.js数组对象的访问、校验与新增功能实现问题求助

问题分析与解决方案

核心问题点

  1. 初始循环不执行:当user.request为空数组时,外层for(let i of user.request)根本不会运行,导致新商品无法添加到数组中。
  2. 判断逻辑错误:遍历现有商品时,只要遇到不匹配的商品就执行添加操作,会导致重复创建对象;且没有处理“遍历完所有商品都没找到匹配项”的情况。
  3. 类型错误:readLine.question()返回的是字符串,直接用+=会导致字符串拼接(比如"1"+"2"变成"12"),需要转为数字类型。

修正后的代码

const readLine = require('readline-sync'); // 假设使用readline-sync库,需确保已安装

let user = {
    name: readLine.question("Name : "),
    location: readLine.question('Location : '),
    request: []
}

while(true){
    const product = readLine.question('input your request : ').toLowerCase();
    // 将total转为数字,确保累加是数值运算
    const total = parseInt(readLine.question("total request : "), 10);
    let found = false;

    // 遍历现有请求,查找是否已存在该商品
    for(let item of user.request){
        // 获取当前商品的名称(每个item只有一个键)
        const existingProduct = Object.keys(item)[0];
        if(existingProduct === product){
            // 找到则累加数量
            item[existingProduct] += total;
            found = true;
            break; // 找到后直接跳出循环,无需继续遍历
        }
    }

    // 如果遍历完都没找到,就新增商品对象
    if(!found){
        const newRequest = {};
        newRequest[product] = total;
        user.request.push(newRequest);
    }

    const isEnough = readLine.question('Enough ?(yes/no)').toLowerCase();
    if(isEnough === 'yes'){
        console.log(user);
        break;
    }
}

关键修改说明

  • 新增found标记:用来跟踪是否在现有请求中找到目标商品,避免循环内错误添加。
  • 正确遍历商品:通过Object.keys(item)[0]获取每个请求对象中的商品名称(因为每个对象只有一个键值对)。
  • 类型转换:用parseInt()将输入的total转为整数,确保数值累加正确。
  • 处理空数组情况:当user.request为空时,found保持false,会执行新增逻辑,解决初始无法添加的问题。
  • 优化循环退出:找到匹配商品后直接break,减少不必要的遍历。

测试验证

输入示例:

Name : Budi
Location : Supeno Street, number 150
input your request : meatball
total request : 5
Enough ?(yes/no) no
input your request : meatball
total request : 7
Enough ?(yes/no) no
input your request : ice tea
total request : 12
Enough ?(yes/no) yes

输出结果:

{
  name: 'Budi',
  location: 'Supeno Street, number 150',
  request: [ { meatball: 12 }, { 'ice tea': 12 } ]
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 11:01:00