我需要创建一个像这样的对象:
{
columns: ["Foo", "Bar", "Baz"],
rows: {
0: [0,1,2],
1: [3,4,5],
},
cells: {
0: "First Cell, First Row",
1: "Second Cell, First Row",
2: "Third Cell, First Row",
3: "First Cell, Second Row",
4: "Second Cell, Second Row",
5: "Third Cell, Second Row"
}
}
其中数字对象键是行 ID 和单元格 ID。创建对象本身并不难,但创建行数组的部分似乎与我正在做的事情过于复杂。
现在我正在做的,对于每一行,每一列,像这样推送cellId++
var cellId = 0;
data.rows.forEach(function (row, rowId) {
newData.rows[rowId] = [];
data.columns.forEach(function (column, columnId) {
newData.rows[rowId].push(cellId++);
});
});
我想要的是类似的东西(伪代码)
data.rows.forEach(function (row, rowId) {
newData.rows[rowId] = new Array({startAt: 0, endAt: 2});
});
有办法做到这一点吗?
最佳答案
map
应该可以帮助您:
var cellId = 0;
data.rows.forEach(function (row, rowId) {
newData.rows[rowId] = data.columns.map(function() { return cellId++; });
});
或者将其用于两个维度:
newData = data.rows.map(function() {
return data.columns.map(function() {
return cellId++;
});
})
关于javascript - 使用生成的 ID 创建 JavaScript 集合的最高效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33642467/