如何在jquery中使用map函数?

use*_*656 2 javascript arrays jquery

我正在尝试add 10使用map按钮单击功能在每个元素中编号(数字)。我试过这样

<!DOCTYPE html>
<html>

  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <script data-require="jquery@*" data-semver="3.1.1" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <style>


    </style>
  </head>

  <body>

    <button class="add">ADD</button>
    <ul class="item">
      <li class="abc">123</li>
      <li class="pp">12</li>
      <li class="abc">78</li>
      <li class="ac">13</li>
    </ul>
    <script>
    $(function () {

        $('.add').click(function () {
            var $items = $('.item li');
            var $newItem =$items.map(function (i,item) {
                console.log($(item).text())
                return $(item).text() +10;
            });
            console.log($newItem)
        });

    });
    </script>
  </body>

</html>
Run Code Online (Sandbox Code Playgroud)

预期输出

133
22
88
23
Run Code Online (Sandbox Code Playgroud)

Ter*_*rry 5

您所需要的实际上是.get()在调用.map()函数后进行链接,这将返回您构造的数组,例如:

var $newItem = $items.map(...).get();
Run Code Online (Sandbox Code Playgroud)

The reason why .get() is needed is because .map() generates an array-like object. Since you have started off with a collection of jQuery objects ($newItem), it will return a DOM node list. In order to get the array you intended, you have to call .get() to return a true array (not a DOM node list). A better explanation of why this is needed is available here: map() get() confusion

On a side note, $(item).text() will not be automatically casted into a Number. This means that if the value of the text if 123, it is actually seen as a string. The + operator will concatenate but not perform addition, i.e. $(item).text() + 10 will give you 12310 instead of 133. In order to cast it to a number, simply prepend a unary + operator in front of the variable: +$(item).text() + 10.

Here is a proof-of-concept example of your scenario, with the two modifications mentioned above applied:

var $newItem = $items.map(...).get();
Run Code Online (Sandbox Code Playgroud)
$(function() {

  $('.add').click(function() {
    var $items = $('.item li');
    var $newItem = $items.map(function(i, item) {
      console.log($(item).text())
      return +$(item).text() + 10;
    }).get();
    console.log($newItem)
  });

});
Run Code Online (Sandbox Code Playgroud)