Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

137
Visualizações
javascript: question about ```.value``` in global/local variable
<html>

<head>
    <title>Example 1</title>
</head>

<body>
    <input type="text" id="item">
    <br>
    <input type="button" value="add item" onclick="addItem()">
    <br>
    <div id="output"></div>

    <script>
        var html = '';
        var output = document.getElementById('output');
        var number = 0;
    
        function addItem(){
            var shoppingList = [];
            var item = document.getElementById('item').value;
            shoppingList.push(item);
            html = (number = (number + 1)) + '. ' + shoppingList + '<br>';
            output.innerHTML = output.innerHTML + html;
        }
    
    </script>

</body>

</html>

When I add x, y, z to shoppingList in the above first example, I receive:

  1. x
  2. y
  3. z

which is that, what I want to receive.

When var item becomes global in the below second example:

<script>
    var html = '';
    var output = document.getElementById('output');
    var item = document.getElementById('item').value;
    var number = 0;
    
    function addItem(){
        var shoppingList = [];
        shoppingList.push(item);
        html = (number = (number + 1)) + '. ' + shoppingList + '<br>';
        output.innerHTML = output.innerHTML + html;
    }
    
</script>

I receive:

1. 2. 3.

So when I move .value from var item to shoppingList.push(item) in the below third example:

<script>
    var html = '';
    var output = document.getElementById('output');
    var item = document.getElementById('item');
    var number = 0;
    
    function addItem(){
        var shoppingList = [];
        shoppingList.push(item.value);
        html = (number = (number + 1)) + '. ' + shoppingList + '<br>';
        output.innerHTML = output.innerHTML + html;
    }
    
</script>

I receive:

  1. x
  2. y
  3. z

Would you Guys be able to explain, why I have to move .value from var item to shoppingList.push(item), if I want to receive the output from the third example (1. x 2. y 3. z), if var item is global, please?

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda