我正在尝试创建一个函数,该函数会选择数组中的随机元素并将其返回。如果拾取的元素本身就是一个数组,则该函数会将拾取的数组传递回自身,并从该新嵌套数组中拾取一个随机元素。如果我使用console.log()输出最终的随机选择的字符串,这似乎是可行的,但是该函数不断返回未定义的值,我不确定为什么。它应该返回字符串
//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)
这是一个JS小提琴,在每次运行时,它都会将结果输出到DOM中的段落元素中:https://jsfiddle.net/oqwgvpyz/
有人可以告诉我为什么pickRandom()函数返回未定义的内容吗?
答案 0 :(得分:1)
您需要return
递归调用:
//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;
}
}