我正在创建一个 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/