map map在jQuery中返回平面数组 [英] map map return flat array in jQuery
本文介绍了map map在jQuery中返回平面数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想拥有数组数组。
我的代码:
image_data = $('.post-entry').map(function() {
return $(this).find('img').map(function() {
var self = $(this);
return {
big: self.hasClass('big') || self.hasClass('medium'),
offset: self.offset(),
width: self.width(),
height: self.height()
};
}).get();
}).get();
但是当我有两个进入后的元素并且每个有4个图像时,我有8个图像的数组。如何获得每个包含4个元素的两个元素的数组?为什么我得到平面阵列?
but when I have two post-entry elements and each have 4 images I have array of 8 images. How can I get array of two elements of 4 elements each? Why I got flat array?
推荐答案
That's because the documentation for map() says (emphasis mine):
该函数可以返回单个数据项或要插入到结果集中的数据
items 数组。 如果返回一个数组,
数组中的元素将插入到集合中。
因此, map()
展平您返回的数组,这种行为是设计使然。
Therefore, map()
flattens the arrays you return, and this behavior is by design.
尝试包装这些数组到另一个数组,因为我相信 map()
只会展平一次:
Try wrapping these arrays into another array, as I believe map()
only flattens once:
image_data = $('.post-entry').map(function() {
return [
$(this).find('img').map(function() {
var self = $(this);
return {
big: self.hasClass('big') || self.hasClass('medium'),
offset: self.offset(),
width: self.width(),
height: self.height()
};
}).get()
];
}).get();
这篇关于map map在jQuery中返回平面数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文