简体   繁体   中英

Push multiple values into an array in Javascript not working

I'm trying to push multiple values into an array based on the elements ID.

I expect the outcome to be 3 and 4 but instead I get 1 2 3 4 . Why is that the case in the following example?

 var myArray = []; $( '#bla' ).each( function() { myArray.push( { test: $( this ).text(), }); }); console.log( myArray ); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <div>1</div> <div>2</div> <div id="bla">3</div> <div id="bla">4</div> </div> 

You are seeing the content of the your HTML, and not the console.log .

This is what you need to fix:

  1. Include jQuery
  2. Use class instead of id - there can be only one id in a document, so you'll get only one result
  3. Look at the console

 var myArray = []; $( '.bla' ).each( function() { myArray.push( { test: $( this ).text(), }); }); console.log( myArray ); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <div>1</div> <div>2</div> <div class="bla">3</div> <div class="bla">4</div> </div> 

First id has to be unique replace id with class and use your snippet

 var myArray = []; $( '.bla' ).each( function() { myArray.push( { test: $( this ).text(), }); }); console.log( myArray ); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <div>1</div> <div>2</div> <div class="bla">3</div> <div class="bla">4</div> </div> 

First of all, you can't have two HTML elements with same id attribute. It is unique indeficator, it should be only one on page.

And second, if you are using your js script from external (not inluded between <scritp></script> ) you should use ( document.ready or in jQuery $(docuemnt).ready(function(){}) [in my case it is short way to do this]), because you don't want to read HTML values before your is not loaded.

 (function () { var myArray = []; $( '.bla' ).each( function() { myArray.push( { test: $( this ).text(), }); }); console.log( myArray ); }()); 
 <div> <div>1</div> <div>2</div> <div class="bla">3</div> <div class="bla">4</div> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM