在循环中将字符串值存储到数组中

3

我想在循环中将所有text的值存储到数组中,这是可能的吗?有人可以给我一些提示如何做到这一点吗?

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

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

});
3个回答

5

只需使用 .map.get - 不需要中间变量或循环

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>


2
人啊,有时候真是最糟糕的存在,不是吗?(开玩笑的。我同意使用.map()是解决这个问题的好方法。) - nnnnnn
1
@aaaaaa - 同样的情况。我不知道,但我怀疑它是反向的,因为您可以使用this来引用元素,所以如果您也想要索引,您只需在回调中定义一个参数即可。 - nnnnnn
1
@aaaaaa - 20% this,20% 闭包,20% 打错字,20% 没有阅读易于获取的文档,20% 帮我编写代码。 (好吧,我不应该说是100%,还有好的、非重复的问题。) - nnnnnn
1
我应该把我的名字改成vvvvvv - Mulan
不是 kkkkkk 吗?我的真名以 "n" 开头和结尾。我妹妹的名字是 Naomi。 - nnnnnn
显示剩余3条评论

2
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

2
您可以使用array.push()将值添加到数组中。
var myArr = []; // define the array
$('#wa li').each(function (i) {
  myArr.push($(this).text()); 
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接