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

函数工厂练习:修复Dog对象控制台输出与咆哮功能异常

修复JavaScript对象方法以实现指定控制台输出

问题排查

  • 模板字符串使用错误:包含${}的字符串误用单引号,必须用反引号``才能解析变量
  • 语法错误:latido方法中${this.nome[])}缺失数组索引,还多了一个右括号
  • 未声明变量:cao = this.nome[i]中的cao未用let/const声明,会污染全局作用域
  • 输出内容不符需求:原方法输出"Au Au",而非要求的"wow"和"grrrrr"
  • 输入逻辑错误:prompt获取狗名后直接转数字当索引,无法匹配对应狗的信息

修复后的代码

const cachorro = {
    "nome": ["Zicao", "Mel", "Brutus", "Bob"],
    "raca": ["Viralata", "Yorkshire", "Chihuahua", "Labrador"],
    "tamanho": ["medio", "pequeno", "menor ainda", "grande"],
    "latido": function(i){
        const cao = this.nome[i];
        // 输出需求的wow消息
        console.log(`${cao}: wow`);
        // 输出咆哮消息
        console.log(`${cao} dog>]: grrrrr`);
    },
    "id": function(i){
        console.log(`
        Nome: ${this.nome[i]}
        Raça: ${this.raca[i]}
        Porte: ${this.tamanho[i]} 
        `);
    }
}

// 根据输入的名字查找对应索引
const dogName = prompt("Name of the dog?");
const dogIndex = cachorro.nome.indexOf(dogName);

// 找到对应狗的索引才执行方法
if (dogIndex !== -1) {
    cachorro.latido(dogIndex);
} else {
    console.log("狗的名字不存在!");
}

修复说明

  • 把所有模板字符串的单引号替换为反引号,确保变量正常解析
  • 修正latido方法的数组索引语法,补全i并移除多余括号
  • 给cao添加const声明,避免全局变量污染
  • 修改latido方法的输出内容,完全匹配需求的消息格式
  • 调整输入处理逻辑:先获取狗名,再用indexOf查找对应数组索引,同时增加名字不存在的判断,避免报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 19:25:19