Misa Misa - 7 months ago 25
Javascript Question

Javascript code getoption


Write a function getoption(m,i) which takes a parameter m, a string of
words seperated by comma ",", and an integer i≥-1 and returns the ith
word in m. If i=-1, then a random word is returned else the ith word
is returned. No error checking is required.

For example, getoption("hello,hi,why,ok",1) must return hello.

getoption("hello,hi,why,ok",4)
must return ok.

getoption("hello,hi,why,ok",-1)
MAY return either hello, hi, who OR
ok.

Hint: You need to split the string m by character ",". This will
result in an array of words. Remember the first word will be index
0!!!! Now if i is greater than -1, return element i+1 since again the
starting index of the array is 0. If i=-1 then generated a random
number from 0 to array.length-1 and then return the word corresponding
to this number.


Hello, I have written the code below and I have a typeerror on line 6 and I don't know how to fix it. Can someone help?



function getoption(m, i) {
var num = m + Math.floor((m + 1) * Math.random());
var j = i.indexOf(num);

while (j != -1) {
num = m + Math.floor((m + 1) * Math.random());
j = i.indexOf(num);
}

return (num);
}

document.write(getoption("hello,hi,why,ok", -1))




Answer

To get a wanted result, I suggest to split the string into a word array with String#split() and store it in an appropriate variable.

Then I suggest to check if the index is equal -1 and get a new index with the length of the array and Math.random().

Now return the element with the index of the word array.

function getoption(words, index) {
    var wordArray = words.split(',');
    if (index === -1) {
        index = Math.floor(Math.random() * wordArray.length);
    }
    return wordArray[index];
}

document.write(getoption("hello,hi,why,ok", -1))