jQuery的.each()
方法是一个迭代函数,用于遍历jQuery对象中的DOM元素或普通数组/对象。当我们需要从这些遍历的元素中提取数据并创建新数组时,可以使用.each()
结合数组操作来实现。
var myArray = []; // 创建一个空数组
$('selector').each(function(index, element) {
// 从元素中提取需要的数据
var data = $(element).text(); // 或其他属性/数据
// 将数据推入数组
myArray.push(data);
});
console.log(myArray); // 输出结果数组
var myArray = $('selector').map(function(index, element) {
return $(element).text(); // 或其他属性/数据
}).get(); // .get()将jQuery对象转换为普通数组
console.log(myArray);
假设我们有以下HTML结构:
<ul id="fruitList">
<li>Apple</li>
<li>Banana</li>
<li>Orange</li>
<li>Grape</li>
</ul>
// 使用.each()
var fruits = [];
$('#fruitList li').each(function() {
fruits.push($(this).text());
});
console.log(fruits); // ["Apple", "Banana", "Orange", "Grape"]
// 使用.map()
var fruits = $('#fruitList li').map(function() {
return $(this).text();
}).get();
console.log(fruits); // ["Apple", "Banana", "Orange", "Grape"]
<div class="product" data-price="19.99" data-id="1001">Product A</div>
<div class="product" data-price="29.99" data-id="1002">Product B</div>
var productPrices = $('.product').map(function() {
return $(this).data('price');
}).get();
console.log(productPrices); // ["19.99", "29.99"]
.map()
时,最后需要调用.get()
将jQuery对象转换为普通JavaScript数组.each()
或.map()
中的index参数.map()
通常比.each()
性能更好这两种方法都能有效地从jQuery的.each循环创建数组,选择哪种取决于个人偏好和具体场景需求。
没有搜到相关的文章