Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store string values to array inside a loop

I want to store all the values of text inside an array in a loop, is it possbile? can someone give me a hint on how to do this?

  $('#wa li').each(function (i) {

    var text = $(this).text();

});
like image 814
hihihihi Avatar asked Sep 28 '26 00:09

hihihihi


2 Answers

Just use .map and .get – there's no need for intermediate variables or loops

const liTexts = 
  $ ('#wa li')
    .map ((idx,elem) => $(elem).text ())
    .get ()
    
console.log (liTexts)
// [ 'one', 'two', 'three' ]
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="wa">
  <li>one</li>
  <li>two</li>
  <li>three</li>
</ul>
like image 94
Mulan Avatar answered Sep 29 '26 14:09

Mulan


var myArr = []; // define the array
$('#wa li').each(function (i) {
  myArr.push($(this).text()); // push the value into the array
});
console.log(myArr); // ['hello', 'world', ...] use the array
like image 45
dhilt Avatar answered Sep 29 '26 14:09

dhilt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!