So I have this code where I have an array of sentences which are being prompted through a switch where the user is to ask how many sentences they want to display 1 - 5. it will then loop through and randomly display the number of sentences requested from the array.
var sentences = ["sentence one", "sentence two", "sentence three",
"sentence 4", "sentence 5"];
function shuffle(a) {
for (i = a.length - 1; i; i--) {
let j = Math.floor(Math.random() * i);
[a[i - 1], a[j]] = [a[j], a[i - 1]];
}
}
var random = prompt("how many sentences do you want?");
switch (random) {
case "1":
shuffle(sentences)
console.log(sentences(0, 1));
break;
case "2":
shuffle(sentences)
console.log(sentences.slice(0, 2))
break;
case "3":
shuffle(sentences)
console.log(sentences.slice(0, 3))
break;
case "4":
shuffle(sentences)
console.log(sentences.slice(0, 4))
break;
case "5":
shuffle(sentences)
console.log(sentences.slice(0, 5))
break;
default:
console.log("incorrect number");
}
The code works fine, but when it returns, it displays the array of course: say if the person wanted 3 sentences:
(3) ["sentence two", "sentence four", "sentence five"]
I want to return the sentences itself and not the array so:
sentence two, sentence four, sentence five
I tried converting to a string with .length but this then returns the number of characters in the string eg prompt entered was 5 so it returns:
sente
Anyone have any ideas, much appreciated :)
array.join.slice()always returns an Array. If you're outputting to HTML you can just assign the Array to theElement.innerHTMLorElement.valueand it gives you a String without[]anyways.switch/case? Justsentences.slice(0, random)