Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

139
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda