call a function within another function in js

Asked

Viewed 2,040 times

1

Hello, to not have to repeat the same code 2x and change only the little one I wanted to do 3 different functions, the vectors() and the two that will call the vectors() and then execute their code, but I’m not getting, what I’m doing wrong?

var i;
function vetores() {
    var n = new Array(10);
    for(i = 0; i < 10; i++) {
        var input = "input";
        var inputNumero = "" + i.toString();
        var inputId = input.concat(inputNumero);
        n[i] = document.getElementById(inputId).value;
    }
}
function calcularMaior() {
    function vetores();
    var max = Math.max(...n);
    alert("Maior valor: " + max);
}
function calcularMenor() {
    function vetores();
    var min = Math.min(...n);
    alert("Menor valor: " + min);
}

  • Remove the keyword function when using the function, it is only used in the definition.

  • still don’t want to go, in the Chrome log that: scripts.js:13 Uncaught Referenceerror: n is not defined at calcularMaior (scripts.js:13) at Htmlbuttonelement.onclick ((index):34) calcularMaior @scripts.js:13 onclick @(index):34 if you wanted a print: https://prnt.sc/jm6pkp

1 answer

1


I didn’t understand the code very well, it’s a bit confusing and I didn’t pass the HTML. I tried to adjust the code to remove the errors as I understood, see if it helps:

function vetores() {    
    var i;
    var n = new Array(10);
    for(i = 0; i < 10; i++) {
        var input = "input";
        var inputNumero = "" + i.toString();
        var inputId = input.concat(inputNumero);
        n[i] = document.getElementById(inputId).value;
    }
    return n;
}
function calcularMaior() {
    var n = vetores();
    var max = Math.max(...n);
    alert("Maior valor: " + max);
}
function calcularMenor() {
    var n = vetores();
    var min = Math.min(...n);
    alert("Menor valor: " + min);
}

  • 1

    thanks for the help, I still don’t know how to use Return, my teacher hasn’t passed it yet and I’m trying to learn from the outside, with his answer already gave me a good idea.

Browser other questions tagged

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