Coursera JavaScript测验输出含 字符串而非换行,请求技术支持
问题分析
你在Coursera小柠檬收据生成器项目中遇到的问题是:本地Chrome控制台和Node.js环境下,代码输出的换行表现正常,但提交测验后未通过,系统提示输出包含\n字符串而非实际换行效果。
环境差异原因
- 本地环境的行为:在Chrome控制台或Node.js中,每次调用
console.log()时,环境会自动在输出内容的末尾添加一个实际的换行符,因此你看到的是每条菜品信息单独占一行,换行表现符合预期。 - Coursera测验系统的逻辑:测验系统通常会捕获程序的输出并转换为字符串形式校验,展示结果时会将实际换行符转义显示为
\n字符串;更关键的是,这类测验往往要求函数返回格式化后的字符串(包含正确换行符),而非直接通过console.log打印输出,你的实现方式与测验评判逻辑不匹配,导致系统判定输出不符合要求。
代码修改方案
将代码改为构建包含换行符的格式化字符串,而非依赖console.log自动添加换行。以下是修改后的代码:
// Given variables const dishData = [ { name: "Italian pasta", price: 9.55 }, { name: "Rice with veggies", price: 8.65 }, { name: "Chicken with potatoes", price: 15.55 }, { name: "Vegetarian Pizza", price: 6.45 }, ] const tax = 1.20; // Implement getPrices() function getPrices(taxBoolean) { let output = ''; for(let i = 0; i < dishData.length; i++){ let finalPrice; if(taxBoolean === true){ finalPrice = dishData[i]['price'] * tax; } else if(taxBoolean === false){ finalPrice = dishData[i]['price']; } else { return "You need to pass a boolean to the getPrices call!"; } // 修复菜品名称与Price之间的空格问题,同时添加换行符 output += `Dish: ${dishData[i]['name']} Price: $${finalPrice}\n`; } // 移除最后多余的换行符 return output.trim(); } // Implement getDiscount() function getDiscount(taxBoolean, guests) { const priceOutput = getPrices(taxBoolean); // 如果getPrices返回错误提示,直接输出 if (priceOutput.includes("You need to pass a boolean")) { console.log(priceOutput); return; } if (typeof guests === "number" && guests > 0 && guests < 30){ let discount = 0; if(guests < 5){ discount = 5; } else { discount = 10; } // 拼接价格信息和折扣信息,确保换行正确 console.log(`${priceOutput}\nDiscount is: $${discount}`); } else { console.log(`${priceOutput}\nThe second argument must be a number between 0 and 30`); } } // 调用示例:比如传入true和3 // getDiscount(true, 3);
修改说明:
getPrices函数:不再直接打印,而是通过字符串拼接生成包含所有菜品信息的文本,每个菜品后添加\n换行符,最后返回格式化后的字符串(移除末尾多余换行)。- 格式修复:在菜品名称和
Price:之间添加了空格,符合常规收据的格式要求(之前的代码缺少这个空格,可能也是测验不通过的隐藏原因)。 getDiscount函数:先获取getPrices返回的格式化字符串,再根据折扣逻辑拼接最终输出,确保整体格式包含正确的换行,同时处理错误提示的情况。
这样修改后,输出的内容会包含实际的换行符,既符合本地环境的显示要求,也能匹配Coursera测验系统的校验逻辑。
内容的提问来源于stack exchange,提问作者Code Noober
相关产品推荐
相关产品推荐

