JavaScript字符串修改及复数化代码逻辑异常问题排查
问题1:如何根据用户输入的提示修改字符串的最后一个字符?
有三种常用方法可以修改字符串的最后一个字符:
- 字符串切片拼接:利用
slice(0, -1)截取原字符串除最后一个字符外的部分,再拼接新字符。
示例代码:const str = "hello"; const newChar = "x"; const modifiedStr = str.slice(0, -1) + newChar; // 结果为"hellx" - 正则替换:使用正则表达式匹配字符串最后一个字符,替换为目标字符。
示例代码:const str = "hello"; const newChar = "x"; const modifiedStr = str.replace(/.$/, newChar); // 结果为"hellx" - 数组转换修改:将字符串转为数组,修改最后一位元素后再转回字符串。
示例代码:const str = "hello"; const newChar = "x"; const strArr = str.split(''); strArr[strArr.length - 1] = newChar; const modifiedStr = strArr.join(''); // 结果为"hellx"
问题2:JavaScript名词复数化代码逻辑错误排查
原代码存在的核心问题
- 运算符优先级错误:
||优先级高于&&,原条件中括号位置错误,导致count判断与后缀判断逻辑混乱。 - 字符串与正则比较无效:
noun.slice(-1) == /o$/是拿单个字符(字符串)与正则对象比较,永远返回false,应使用正则的test()方法判断匹配。 - 缺少普通复数分支:未处理普通名词加
s的情况(如apple→apples)。 - 语法错误:
else(result = ...)写法不符合JS规范,需用大括号包裹代码块。 - 未覆盖
fe结尾规则:原需求要求处理fe结尾的名词,但代码仅判断了f结尾。 - count类型未转换:
prompt()返回字符串,直接与数字比较可能出现隐式转换问题,需转为数字类型。
修正后的代码
// Returns the number and pluralized form, like "5 cats" or "1 dog", given // a noun and count. However, there are a few exceptions. In this exercise, // add "es" in the following cases: // 1. the given noun ends with 'o'. For example, '5 potatoes'. // 2. the noun ends in "f" or "fe" change the "f" to a "v" and add "-es." // 3. the noun ends in "y", change the "y" to a "i" and add "-es." // HINT: to replace the last character, you can use `replace()` with Regex. // For example, if you would like to replace the last 'e' with 'o' in a string `str`, // you can use `str.replace(/e$/, 'o')`. const noun = prompt("Enter a noun"); // 将输入的count转为数字,避免字符串与数字比较的隐式转换问题 const count = Number(prompt("Enter a number")); console.log(noun); console.log(count); let result; // 判断是否需要复数形式:count不为1且是有效数字 const needsPlural = count !== 1 && !isNaN(count); if (needsPlural) { // 按规则优先级处理:fe结尾 > f结尾 > y结尾 > o结尾 > 普通加s if (/fe$/.test(noun)) { result = `${count} ${noun.replace(/fe$/, 'ves')}`; } else if (/f$/.test(noun)) { result = `${count} ${noun.replace(/f$/, 'ves')}`; } else if (/y$/.test(noun)) { result = `${count} ${noun.replace(/y$/, 'ies')}`; } else if (/o$/.test(noun)) { result = `${count} ${noun}es`; } else { // 普通名词直接加s result = `${count} ${noun}s`; } } else { // 不需要复数的情况(count为1或非有效数字) result = `${count} ${noun}`; } // DO NOT CHANGE THIS. console.log(result);
修正后对应测试用例的修复说明
0 degrees:原代码输出0 degree,修正后输出0 degrees(普通复数加s)0 thieves:原代码输出0 thief,修正后输出0 thieves(f结尾替换为ves)2 apples:原代码输出2 apple,修正后输出2 apples(普通复数加s)10 balloons:原代码输出10 balloon,修正后输出10 balloons(普通复数加s)3 knife:原代码输出3 knife,修正后输出3 knives(fe结尾替换为ves)-40 degrees:原代码输出-40 degree,修正后输出-40 degrees(普通复数加s)
内容的提问来源于stack exchange,提问作者Youssef Shehata
相关产品推荐
相关产品推荐

