javascript - map map 在jQuery中返回平面数组

标签 javascript jquery arrays

我想要数组的数组。

我的代码:

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 个元素?为什么我得到平面数组?

JSFIDDLE

最佳答案

这是因为 map() 的文档说(强调我的):

The function can return an individual data item or an array of data items to be inserted into the resulting set. If an array is returned, the elements inside the array are inserted into the set.

因此,map() 会展平您返回的数组,这种行为是设计使然。

尝试将这些数组包装到另一个数组中,因为我相信 map() 只会展平一次:

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();

关于javascript - map map 在jQuery中返回平面数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19160264/

相关文章:

javascript - 如何处理我类的点击事件

javascript - htmlCollection child 不在 IE 中工作

javascript - 如何在 JavaScript/Jquery 中切片已经存在于另一个数组中的数组元素

javascript - 根据特定条件拖放列表

c - 为什么我的二维数组代码可以使用 malloc(0)?

javascript - 如何使用 javascript 或 lodash 过滤嵌套数组

javascript - 菜单打开时如何展开DIV

javascript - 下拉按钮只能使用一次

jQuery 选项卡。 。 。我需要做这一切! (鼠标悬停,从选项卡单击导航并根据页面选择选项卡)

javascript - js 不传递 php 邮件的表单数据