首页 > 解决方案 > 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?

标签: javascript

解决方案


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;
    }
}

推荐阅读