我有一个数组:
var cells = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
我的 JavaScript 代码解析这个数组并绘制为表格。
现在我想添加函数来简化向表中添加行和单元格的过程,所以我从以下代码开始:
Array.prototype.tsoAddRow = function () {
this.push([]);
return this[this.length-1];
};
Array.prototype.tsoAddCell = function (value) {
this.push(value);
};
cells.tsoAddRow().tsoAddCell("123");
它工作正常,结果是 Array [ Array[1] ]
但我需要更多。
我如何改进这个功能,以便我能够像这样使用它们:
cells.tsoAddRow().tsoAddCell("1").tsoAddCell("2").tsoAddCell("3")
.tsoAddRow().tsoAddCell("4").tsoAddCell("5").tsoAddCell("6")
.tsoAddRow().tsoAddCell("7").tsoAddCell("8").tsoAddCell("9")
或者类似的链接方式。表格可能要复杂得多,例如,这里是另一个表格:
cells = [
[
"Lorem ipsum",
"Lorem ipsum2",
[
["111", "222"]
]
],
[
"Lorem ipsum1",
"Lorem ipsum12"
],
[
"Lorem ipsum2",
"Lorem ipsum22"
],
更新1:
感谢@binariedMe,我有解决方案,这里是上面数组的替代方案,但仅使用链式函数:
cells
.tsoAddRow()
.tsoAddCell("Lorem ipsum")
.tsoAddCell("Lorem ipsum")
.tsoAddCell(
new Array().tsoAddRow()
.tsoAddCell("111")
.tsoAddCell("222")
)
.tsoAddRow()
.tsoAddCell("Lorem ipsum1")
.tsoAddCell("Lorem ipsum12")
.tsoAddRow()
.tsoAddCell("Lorem ipsum2")
.tsoAddCell("Lorem ipsum22");
最佳答案
为 tsoAddCell 创建此函数
Array.prototype.tsoAddCell = function (value) {
this.length && this[this.length-1].push(value); return this;
};
并使 tsoAddRow 函数像这样:
Array.prototype.tsoAddRow = function () {
this.push([]);
return this;
};
说明:
添加单元格应在添加的最后一行上完成,但要链接我们每次返回原始数组所需的所有内容,以便我们可以对其执行下一个任务。 因此,您需要从每个函数返回此值。
关于javascript - 通过链式函数调用将元素添加到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43223218/