簡體   English   中英

如何用數據形成 arrays 的數組

[英]how to form an array of arrays with data

我需要像這樣創建一個 arrays 數組:

var serviceCoors = [
        [50, 40],
        [50, 50],
        [50, 60],
    ];

從帶有數據的元素:

<div data-latitude="10" data-longitude="20" class="service-points__map"></div>
<div data-latitude="20" data-longitude="10" class="service-points__map"></div>

我正在嘗試這個:

var test = [];
$('.service-points__map').each(function(){
        var test2 = $(this).contents();
        var items = [];
        $.each(test2, function(i, val) {
            items.push(val.data);
        });
        test.push(items);
    });

但它不起作用。 我有 2 個 arrays,但它們是空的。

哦,你所做的是... var test2 = $(this).contents(); 不是你需要使用的正確的東西。 您應該使用.data()解構 object

 var test = []; $('.service-points__map').each(function() { var { longitude, latitude } = $(this).data(); test.push([longitude, latitude]); }); console.log(test);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div data-latitude="10" data-longitude="20" class="service-points__map"></div> <div data-latitude="20" data-longitude="10" class="service-points__map"></div>

我得到了 output 為:

[
  [ 20, 10 ],
  [ 10, 20 ]
]

最初我打算建議jQuery 的map方法,但是 -顯然是設計- 它會自動展平 output 只能通過將坐標嵌套在另一個數組中來解決。 它似乎也自動將字符串強制轉換為數字,這在您的情況下很有用,但它似乎做出了很多您可能不想要的決定。

 const out = $('div').map((i, el) => { const { latitude, longitude } = $(el).data(); return [[ latitude, longitude ]]; }).toArray(); console.log(out);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div data-latitude="10" data-longitude="20" class="service-points__map"></div> <div data-latitude="20" data-longitude="10" class="service-points__map"></div>

Native JS 沒有這個問題。 只需拿起元素,然后遍歷它們,返回嵌套坐標的新數組。

 const divs = document.querySelectorAll('div'); const coords = Array.from(divs).map(div => { const { latitude, longitude } = div.dataset; return [ +latitude, +longitude ]; }); console.log(coords);
 <div data-latitude="10" data-longitude="20" class="service-points__map"></div> <div data-latitude="20" data-longitude="10" class="service-points__map"></div>

附加文件

或者,您可以使用純 JS 代替 jQuery。 您需要做的就是獲取元素,對其進行迭代,創建每個項目的屬性數組,並將其推送到test數組中。

 const test = []; const items = document.querySelectorAll('.service-points__map'); items.forEach(item => { test.push([ parseInt(item.getAttribute('data-latitude')), parseInt(item.getAttribute('data-longitude')), ]); }); console.log(test);
 <div data-latitude="10" data-longitude="20" class="service-points__map"></div> <div data-latitude="20" data-longitude="10" class="service-points__map"></div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM