javascript - Recursive function to return random element in an array returning undefined
问题描述
I'm trying to make a function that picks a random element in an array and returns it. If the picked element is in itself an array, then the function passes that picked array back into itself and picks a random element from within that new nested array. It seems to be working if I use console.log() to output the final randomly picked string, but the function keeps returning undefined and I'm not sure why. It should be returning the string
//picks a random entry from an array, recursively
function pickRandom(inputArr) {
//if the argument passed into the function is an array, then
if (Array.isArray(inputArr) === true) {
//pick a random element from that array, and run it back through the function
pickRandom(inputArr[Math.floor(Math.random() * inputArr.length)]);
//otherwise, just change the text content in the DOM to the argument and also return the argument
} else {
document.getElementById('textOutput').textContent = inputArr;
return inputArr;
}
}
var testArr =
[
["string 1", "string 2"],
"string 3"
]
pickRandom(testArr)
Here is a JS fiddle where every time you run it, it outputs the result into a paragraph element in the DOM: https://jsfiddle.net/oqwgvpyz/
Can someone please tell me why the pickRandom() function is returning undefined?
解决方案
You need to return
the recursive call:
//picks a random entry from an array, recursively
function pickRandom(inputArr) {
//if the argument passed into the function is an array, then
if (Array.isArray(inputArr) === true) {
//pick a random element from that array, and run it back through the function
return pickRandom(inputArr[Math.floor(Math.random() * inputArr.length)]);
//otherwise, just change the text content in the DOM to the argument and also return the argument
} else {
document.getElementById('textOutput').textContent = inputArr;
return inputArr;
}
}
推荐阅读
- c# - 如何向 WPF 应用程序图标添加通知徽章,以便它出现在应用程序图标出现的所有位置,而不仅仅是窗口标题栏?
- python - 为什么`await asyncio.create_task()`的行为与将其分配给变量时不同?
- python - 使用 groupby+apply 对每个组进行聚类 - 性能问题
- c - 当数字不是分数时停止计算
- javascript - 错误:找不到模块“/Users/MYNAME/Desktop/Projects/MYPROJECTNAME”
- r - rvest:无法使 follow_link() 或 jump_to 移动到链接的无序列表
- javascript - 如何为 Safari 做模板字符串?
- bash - 从/etc/fstab 读取除注释行之外的所有行,包含'bind|swap|shm' 的行并打印其中未安装的行?
- c# - 使用 C# 和 Xamarin 计算轮子的旋转次数
- python - 如何在Python中删除单词之间的多个空格,没有前导空格