Ваш код не делает то, что вы думаете. Он создает объект, а не массив.
Кроме того, понимает, что индексы массива начинают отсчет от 0, в то время как длина начинает отсчет с 1
Кроме того, при получении случайного числа, если вы хотите, чтобы иметь возможность получить 0 в качестве возможного результата (который вам потому что, как я уже сказал, индексы массива начинаются с 0), вы должны округлять, а не вверх.
Наконец, на самом деле нет необходимости в вашей функции buildArray
, так как вы можете создавать массивы (и автоматически рассчитывать их размер/длину) гораздо проще.
Однако, если вы должны были сделать эту функцию, это то, что он должен выглядеть следующим образом:
function buildArray(size){
// Create new, empty array
var result = [];
// Se the size of the array to the size passed in
// As stated, this is not really needed since arrays calculate
// their length automatically.
result.length = size;
// Return new, empty array
return result
}
// Use the function, don't instantiate it, just call it
var NumberOfWords = 2;
var words = buildArray(NumberOfWords);
// Populate the array, indexes start from 0, length starts from 1
words[0] = "word 1";
words[1] = "word 2";
// NOTE: All of the above code could really just be replaced by:
//var words = ["word 1", "word 2"];
// Get random word from the array and display in the textarea:
function pickRandomWord(frm) {
// Get random number between 0 and the largest index used in the array
// You should be rounding down here (so that 0 is a possibility)
var rnd = Math.floor(Math.random() * NumberOfWords);
document.querySelector("textarea").value = words[rnd];
}
// Set up button to call the function
document.querySelector("button").addEventListener("click", pickRandomWord);
<form>
<textarea></textarea>
<button>Get random array element</button>
</form>
использование 'console.log' – orvi
Что делает верхний код нужно сделать с нижний код 'myFunction'? –
верхний код генерирует [число] слова из массива, это слово отображается в textarea – Tarasovych