3

I am trying to generate a random words and push each one individually to the array, the problem is, i am getting list of words that starts from the first letter increased by one like this:

['a','ab','abc','abcd'] and so on

here is my code:

var word = "";
var texts = [];
var letters = "абвгдеёжзийклмнопрстуфхцчшщъыьэюя";
for (var i = 0; i < 10; i++){
    word += letters.charAt(Math.floor(Math.random() * letters.length))
    texts.push(
        {
            "id":i,
            "name":word,
            selected: false
        }
    )
}

what i need is to push a complete word to the list.

4
  • 1
    To do it like this you will need two loops: one from 0 to numWords and inside that one from 0 to numLetters. Commented Sep 22, 2018 at 1:33
  • For the first time i did it with two loops, but my browser got freezed!! i think i did it the wrong way but thank you @MarkMeyer for your interest :) Commented Sep 22, 2018 at 1:41
  • Russian w/ a handle about a hacking movie, asking for help in generating random words… what's your purpose? Commented Sep 22, 2018 at 2:13
  • @vol7ron its not what you are thinking about, its just a small app that i am creating using Flask and VueJS :) Commented Sep 22, 2018 at 2:19

2 Answers 2

3
var texts = [];
var letters = "абвгдеёжзийклмнопрстуфхцчшщъыьэюя";
var wordLength = 5;
for (var i = 0; i < 10; i++){
    let word = "";
    for(var j = 0; j < wordLength; j++) {
      word += letters.charAt(Math.floor(Math.random() * letters.length));
    }
    texts.push(
        {
            "id": i,
            "name": word,
            selected: false
        }
    )
}

You need to use another one loop for generate a words. New word's loop each time.

Sign up to request clarification or add additional context in comments.

1 Comment

I am glad to help you. P.S. Last time (when your "browser got freezed") might have been infinity loop.
0
    var word = "";
var texts = [];
var letters = "abcdefghijklmn";
for (var i = 0; i < 10; i++){
    word = letters.slice(1,i)
    texts.push(word);
}
alert(texts);

Oh, sorry you need it random; how about this

var word = "";
var texts = [];
var letters = "abcdefghijklmn";
var l = letters.length;
var textsNum = 10;
for (var v = 0; v < textsNum; v++) {
  for (var i = 0; i < l; i++) {
    word += letters[Math.floor(Math.random() * l)];
  }
  texts.push(word);
  word = '';
}

console.dir(texts);

1 Comment

You see , the result is the same as my code, but thanks for your interest :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.