javascript - 转换 2D 数组理解 |米xn尺寸

标签 javascript arrays google-apps-script list-comprehension

我正在创建一个 Google App 脚本,并在内部尝试创建一个表格结构,其中单元格数据是行标题的值 + 列标题的值。

我有以下代表日期和时间的标题...

var tableHeadings = ["M", "T", "W", "TH", "F", "S", "SU"]
var tableHours = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]

我希望内容等于“M0”,“M1”,“M2”,...,“TH1”,...等。所以列数是7,行数是10.

我正在研究如何做到这一点并发现了数组推导式,但我很快发现这些现在不受支持,我们不应该使用它们。

var table = [for (day of tableHeadings) [for (hour of tableHours) day + hour]];

FYI, I don't know if I need to swap the 2 for-clauses yet. I am representing the columns as the days of the week. Also, I don't know if this works on m x n arrays as Google App Script does not allow for this syntax, but if you scroll down to Array comprehensions with two arrays to see an example I used as inspiration.

在大多数文档中,我已经能够找到如何将单数组数组理解转换为使用映射和过滤器,但我还没有找到有关如何转换双数组 (m x n) 数组理解的任何内容。一些文档讨论了双数组 (m x m) 数组理解,但没有讨论如何转换它们。

是否有一种简单的方法来转换双数组 (m x n) 数组理解?具体来说,该解决方案需要适用于 (m x n) 数组。

最佳答案

您可以通过嵌套 Array#map 来实现此目的来电:

var tableHeadings = ["M", "T", "W", "TH", "F", "S", "SU"];
var tableHours = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];

var result = tableHeadings.map(function(day) {
  return tableHours.map(function(hours) {
    return day + hours;
  });
});

console.log(result);

使用 ES6 箭头函数,您可以拥有一个衬垫:

const tableHeadings = ["M", "T", "W", "TH", "F", "S", "SU"];
const tableHours = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];

const result = tableHeadings.map((day) => tableHours.map((hours) => day + hours));

console.log(result);

关于javascript - 转换 2D 数组理解 |米xn尺寸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48090106/

相关文章:

c# - 为什么我的数组抛出超出范围异常错误?

arrays - 从txt文件中逐个字符读取,然后写入C中的另一个文件?

javascript - 使用 Google 脚本将变量推送到 HTML 中

javascript - Google Apps 脚本 - 如何发送包含数组内容的电子邮件?

javascript - Material UI 中的多行占位符文本

javascript - 如何将表单字段转换为 Json 对象?

javascript - 拖动时将 Google map 标记保持在 map 中心?

javascript - 无法使用 JavaScript 在网页上加载 XML 文档

有效地基于属性的Javascript对象求和值

javascript - 在 Google 表格自定义功能中引发自定义异常和错误消息?