遍历值为数组的对象及自定义函数返回undefined问题排查
问题一:遍历对象并为每个键取一个数组值
给定如下结构的对象:
const obj = { 'keyA': ['value 1', 'value 2'], 'keyB': ['value 3', 'value 4'] }
要为每个键返回其数组中的任意一个值,可采用以下几种实现方式:
方式一:使用
Object.entries遍历键值对
遍历对象的每一组键值对,对每个数组随机选取一个元素:const result = {}; for (const [key, arr] of Object.entries(obj)) { const randomIndex = Math.floor(Math.random() * arr.length); result[key] = arr[randomIndex]; } console.log(result); // 示例输出:{ keyA: 'value 2', keyB: 'value 3' }方式二:使用
Object.keys遍历键名
通过键名获取对应数组后选取元素:const result = {}; Object.keys(obj).forEach(key => { const arr = obj[key]; result[key] = arr[Math.floor(Math.random() * arr.length)]; }); console.log(result);
如果仅需返回指定单个键及其对应数组的一个值,比如目标键为keyA:
const getRandomValue = (obj, targetKey) => { if (!obj[targetKey]) return '无效的键'; const arr = obj[targetKey]; return { [targetKey]: arr[Math.floor(Math.random() * arr.length)] }; }; console.log(getRandomValue(obj, 'keyA')); // 示例输出:{ keyA: 'value 1' }
问题二:代码返回
undefined的原因及修复 你的代码存在多处逻辑错误,导致调用后返回undefined,具体问题和修复方案如下:
1. 循环条件写反且存在无效分号
循环条件写成了i > noun.length,正确逻辑应为i < noun.length;且每个循环末尾多了分号,导致循环体为空,后续代码根本不会进入循环执行。
2. 参数与全局变量重名
函数参数noun覆盖了全局的noun数组,调用userChoice('I')时,函数内的noun是字符串'I'而非全局数组,noun.length为1,循环直接跳过。
3. this使用错误
普通函数中this.noun无意义,你需要直接使用函数参数或全局变量(需避免参数与全局变量重名)。
4. 数组比较逻辑错误
i === [0]、i === [1] || [2]的写法完全错误:数组与数字永远不会相等,[1] || [2]的结果为[1](永远为真),导致逻辑分支判断失效。
5. 函数无返回值
函数内仅用console.log输出内容,但未设置return语句,因此调用userChoice('I')时会返回undefined,外层console.log自然会输出undefined。
修复后的代码
const nouns = ['I', 'We', 'You']; const adverbA = ['will be', 'can be', 'are']; // 对应We和You const adverbB = ['will be', 'can be', 'am']; // 对应I const verbs = ['special', 'important', 'powerful', 'loved', 'beautiful', 'amazing']; const userChoice = (inputNoun) => { // 查找输入名词在数组中的索引 const index = nouns.indexOf(inputNoun); if (index === -1) { return 'Invalid Entry'; } // 根据索引选择对应副词数组 const adverbs = index === 0 ? adverbB : adverbA; // 随机选取副词和动词 const randomAdverb = adverbs[Math.floor(Math.random() * adverbs.length)]; const randomVerb = verbs[Math.floor(Math.random() * verbs.length)]; // 返回拼接后的字符串,而非直接console.log return `${inputNoun} ${randomAdverb} more ${randomVerb} than ${inputNoun} know!`; }; // 打印函数返回值 console.log(userChoice('I')); // 示例输出:I am more amazing than I know!
修复后函数会返回拼接好的字符串,调用后console.log将输出正确内容,不会返回undefined。
内容的提问来源于stack exchange,提问作者mthom22
相关产品推荐
相关产品推荐

