如何用JavaScript函数打印键为奇数的对象值?现有代码输出随机引用
解决方法:筛选并打印键为奇数的对象值
嘿,我懂你要做的事了——你原本想让函数打印出对象里键为奇数的那些引用语句,但当前代码看起来是朝着随机输出的方向写的对吧?咱们来调整一下代码,达成你的目标。
首先先把你的引用对象补全(看起来最后一句没写完,我帮你补了个合理的收尾):
const quotes = { 0: "All computers wait at the same speed.", 1: "A good programmer looks both ways before crossing a one-way street.", 2: "Computers do not solve problems, they execute solutions.", 3: "The best thing about a boolean is even if you are wrong, you are only off by a bit.", 4: "Ubuntu is an ancient African word, meaning 'humanity to others'." };
接下来分两种常见场景给你实现方案:
场景1:打印所有键为奇数的引用
如果要把所有键是奇数的引用全部打印出来,可以这么写:
function displayOddKeyQuotes() { const quotes = { 0: "All computers wait at the same speed.", 1: "A good programmer looks both ways before crossing a one-way street.", 2: "Computers do not solve problems, they execute solutions.", 3: "The best thing about a boolean is even if you are wrong, you are only off by a bit.", 4: "Ubuntu is an ancient African word, meaning 'humanity to others'." }; // 遍历对象所有键,筛选出奇数键并打印对应值 Object.keys(quotes).forEach(key => { const numKey = parseInt(key); if (numKey % 2 !== 0) { console.log(quotes[key]); } }); } // 调用函数执行 displayOddKeyQuotes();
运行后控制台会输出键为1和3的两句引用。
场景2:从奇数键的引用中随机选一个打印
如果你是想从所有奇数键的引用里随机挑一个输出(而不是全部),可以调整成这样:
function displayRandomOddQuote() { const quotes = { 0: "All computers wait at the same speed.", 1: "A good programmer looks both ways before crossing a one-way street.", 2: "Computers do not solve problems, they execute solutions.", 3: "The best thing about a boolean is even if you are wrong, you are only off by a bit.", 4: "Ubuntu is an ancient African word, meaning 'humanity to others'." }; // 先筛选出所有奇数键对应的引用,存入数组 const oddQuotes = Object.entries(quotes) .filter(([key]) => parseInt(key) % 2 !== 0) .map(([_, quote]) => quote); // 有符合条件的引用就随机选一个打印,否则提示无结果 if (oddQuotes.length > 0) { const randomIndex = Math.floor(Math.random() * oddQuotes.length); console.log(oddQuotes[randomIndex]); } else { console.log("没有找到键为奇数的引用"); } } // 调用函数执行 displayRandomOddQuote();
关键逻辑说明:
- 用
Object.keys()或Object.entries()遍历对象的键值对,能完整拿到所有键信息 - 把字符串类型的键转成数字(对象的键默认是字符串),再用
numKey % 2 !== 0判断是否为奇数 - 随机选择的逻辑是先收集符合条件的引用到数组,再用
Math.random()生成随机索引
内容的提问来源于stack exchange,提问作者Bala Hantsi
相关产品推荐
相关产品推荐

