Function does not return values

Asked

Viewed 76 times

-1

I’m beginner in JS and I’m having some problems with the function below. I am unable to return the array with this code. It is only returned when I remove "vet = []" where I empty it (something needed).

The function must generate and return a randomly generated vector with defined size from a selection made on the page where the user chooses 10, 100, 1000, 10000 or 100000 elements for the vector.

function Valeatorio(vet){
    let tamanho = document.getElementById("TVetor").value
    vet = [] //Removendo esse trecho o Array retorna
    if (tamanho > 0 && tamanho <= 10){
        console.time("Vetor Aleatório")
        for (let i = 0; i < tamanho; i++) {
                vet.push(parseInt(Math.random() * 100))
            } 
        console.timeEnd("Vetor Aleatório")
        console.log(vet)
        document.getElementById('VetorG').innerHTML = `<strong>Vetor gerado:</strong><br>${vet}`
    } else if(tamanho > 10){
        console.time("Vetor Aleatório")
        for (let i = 0; i < tamanho; i++) {
                vet.push(parseInt(Math.random() * 100))
            }
        console.timeEnd("Vetor Aleatório")
        console.log(vet)
        document.getElementById('VetorG').innerHTML = "<strong>Vetor gerado:</strong><br>Tamanho máximo permitido para visualização ultrapassado" 
    } 
    return [vet]
} 

Thank you!

  • 1

    Hello @Galbert22, Welcome to Sopt, before you start a look at our [Tour]. On your question whether your intention is to return a Array with these values, it seems to me that this missing open and close conchete, leaving +/- like this return [ tamanho, vet1, vet2, vet3 ];, for this reason I am signaling as typo =D

  • 1

    In addition, the vet1 = [], vet2 = [], vet3 = [] is over-writing the parameters vet1, vet2 and vet3. Is that really what you want to do? And more: Valeatório is not a valid function name in Javascript, as it includes an accent (ó).

  • I ended up modifying the code in the meantime, I will edit the main post leaving it as is. Using the brackets to return the value did not help and, yes, overwrite the parameters whenever the function is called is what I would like to do.

  • Could you edit your question again to add the HTML code snippet that is required for the code to work? If possible, add a snippet executable.

  • 1

    Its conditions do not cover all possibilities, if tamanho is negative the function returns nothing, and apparently you expect your function to always return something. Another thing, so you get the argument vet if you will always overwrite it every function call? You could just create an empty array when you need it and that’s it.

  • 1

    Why do you return [vet], and not vet?

  • 1

    You should also note that input.value returns a string, so you should do the integer conversion before using it for comparisons. You can use the method parseInt(input.value, 10) (I always use the 2nd parameter, Radix, to ensure that the browser does not interpret zero-started numeric strings as octal)

  • Also... what is the need for parseInt in the Math.random(), that already returns an integer? (In: parseInt(Math.random() * 100))

  • Luiz, Math.random() returns a float.

  • And it would be better to use the function Math.floor() with Random, the mathematical operation is more efficient than the whole string Parsing process. Ex.: Math.floor(Math.random() * 100);

  • Anyway Galbert22, there is a lot that can be improved in your function, only you can not simply change your code to what I think is best. It would be nice if you explained what this function should do and what the result of it will be used for. That way we could help you much more quickly and effectively.

  • I edited again the original post with information on the usefulness of this interview, thanks @fernandosavio for the tip.

  • As I said in the post, if I don’t clear the vector when the function is called, it returns without any problem. But cleaning is necessary to not accumulate the numbers whenever it is going to generate the random.

Show 8 more comments

1 answer

2

I’ll try to recreate that function based on what you said in:

The function must generate and return a randomly generated vector with defined size from a selection made on the page where the user chooses 10, 100, 1000, 10000 or 100000 elements for the vector.

And I’ll also assume that arrays with more than 10 elements should not be shown to the user for reasons of presentation from what I’ve seen of their code.

Then I’ll break the problem in pieces:

  1. Create a function that generates an array of N random numbers
  2. Receive the array size of a user input
  3. Present (or not) the new vector to the user

I will try to leave it well explained so that you understand the reasons for my decisions:

1. a function that generates an array of N random numbers

The function below generates an array of the size defined by the argument tamanho filled with random values between 0 and 99.

function gera_array(tamanho) {
    // Cria o novo array
    let novo_array = [];

    // Popula o array
    for (let i=0 ; i < tamanho ; i++) {
        novo_array.push(Math.floor(Math.random() * 100))
    }

    // Retorna o novo array populado
    return novo_array;
}

2. Receive the array size of a user input

To receive the value of a <input> user will just convert the attribute input.value for an integer and use it as parameter for the function gera_array.

// Guarda a referência para o elemento HTML
let input_tamanho = document.querySelector("#tamanho")
// Converte `input.value` para inteiro
let tamanho = parseInt(input_tamanho.value, 10)

Note that I created a variable input_tamanho keeping the reference to the HTML element. I did this because searching the DOM tree is computationally expensive for the browser, but as I saved your reference just use input_tamanho whenever I need it without the browser having to search for the element in the DOM again.

Note: The hint to save the reference to the HTML element is not required, but everyone should do this and understand why.

3. Presenting (or not presenting) the new vector to the user

I will create a function that reads the array and returns a string to be placed in HTML as feedback for the user.

function array_to_string(array) {
    if (array.length <= 10) {
        return "[" + array.join(", ") + "]"
    else {
        return "Array muito grande para visualizar"
    }

Now putting it all together we would have:

function gera_array(tamanho) {
    let novo_array = [];

    for (let i=0 ; i < tamanho ; i++) {
        novo_array.push(Math.floor(Math.random() * 100))
    }
    return novo_array;
}

function array_to_string(array) {
    if (array.length <= 10) {
        return "[" + array.join(", ") + "]"
    } else {
        return "Array muito grande para visualizar"
    }
}

// referências:
let input_tamanho = document.querySelector("#tamanho")
let btn = document.querySelector("#btn")
let resultado = document.querySelector("#resultado")

btn.addEventListener('click', function() {
    let tamanho = parseInt(input_tamanho.value, 10)
    let vetor = gera_array(tamanho)
    
    resultado.innerHTML = array_to_string(vetor)
})
<input id="tamanho" type="number" value="10">
<button id="btn">Criar array</button>

<p id="resultado">Resultado...</p>

  • I learned a few things from your post, thank you very much. But I still don’t understand why my function doesn’t return the array.

  • Another time I edit and improve the answer. : D

  • @Galbert22 Its function returns normally. Behold

Browser other questions tagged

You are not signed in. Login or sign up in order to post.