如何将.each()中的值推送到jQuery中的一个数组?

时间:2015-12-02 16:26:11

标签: jquery

我有这个:

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;

public class CloudFlareTest {

    public static void main(String[] params){
        HttpClient httpClient = HttpClients.createDefault();
        HttpGet getMethod = new HttpGet("https://your.domain.com/path/to/yourrequest");

        getMethod.addHeader(":authority", "your.domain.com");
        getMethod.addHeader(":method","GET");
        getMethod.addHeader(":path","/path/to/yourrequest");
        getMethod.addHeader(":scheme","https");

        try {
            HttpResponse httpResponse = httpClient.execute(getMethod);

            if(httpResponse.getStatusLine().getStatusCode() == 200){

                System.out.println("Done: " + httpResponse.getEntity().getContentLength());
            }
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

我将获得10个数据测试值,我想将它们推送到数组'y',如下所示:

$(".section").each( function() {
    var x = $(this).attr('data-test');
    var y =[];
    y.push(x);
});

如何将x“拆分”为每个值并将它们推送到y?

编辑:

HTML例如:

['1','2','3','4','5','6'...'10']

等等

3 个答案:

答案 0 :(得分:7)

根据您的HTML示例,您可以使用map()为您创建数组:



var y = $(".section").map(function() {
    return $(this).data('test');
}).get();

// This is only for display purposes
$('div').text(JSON.stringify(y)); 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li class="section" data-test="15">15</li>
  <li class="section" data-test="6">6</li>
  <li class="section" data-test="78">78</li>
</ul>

<div></div>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

使用ES6的强制性香草回答

String msg = in.toString(CharsetUtil.UTF_8);
in.readerIndex(in.readerIndex() + in.readableBytes());
System.out.println("Decode:"+msg);

您遇到的问题是您在每次迭代时重置数组var y = []; Array.from(document.querySelectorAll(".section")).forEach(x => { y.push(x.getAttribute("data-test")) }); ,从而删除以前的索引。

y将从Array.from()返回的NodeList转换为更好的可迭代,(您也可以使用querySelectorAll而不是map)然后只需推送{{的数据属性1}}进入数组

答案 2 :(得分:0)

$.merge()可用于将项连接到数组

&#13;
&#13;
var y = [];

$(".section").each(function() {
  $.merge(y, [$(this).data("test")])
});

console.log(y)
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<li class="section" data-test="15"></li>
<li class="section" data-test="6"></li>
<li class="section" data-test="78"></li>
&#13;
&#13;
&#13;