Sim*_*n H 5 javascript arrays underscore.js
我正在尝试切换到函数式编程,并希望使用下划线来实现JavaScript.
但我被困在一垒.我根本无法创建一个数组并使用命令式语言,我似乎无法正确地转换它们:n.length是正确的,但是n [0] .length是未定义的(参见小提琴)
var a = new Array(5);
for (i = 0; i < a.length; i++) {
a[i] = new Array(6);
}
var n = _.map(a, function (row, rowIdx) {
_.map(row, function(col, colIdx) {
return rowIdx * colIdx
});
});
console.log(a.length)
console.log(n.length)
console.log(a[0].length);
console.log(n[0].length);
Run Code Online (Sandbox Code Playgroud)
要使用下划线“功能性地”创建 5 x 6 矩阵,您可以执行以下操作:
var matrix = _.range(5).map(function (i) {
return _.range(6).map(function (j) {
return j * i;
});
});
Run Code Online (Sandbox Code Playgroud)
该_.range函数(文档)是创建填充连续数字的数组的简写。例如,_.range(5)返回数组[0,1,2,3,4]。范围从零开始。
如果您不想使用_.range,您可以通过使用数组文字来使用原始 JavaScript 来完成此操作:
var matrix = [0,1,2,3,4].map(function (i) {
return [0,1,2,3,4,5].map(function (j) {
return j * i;
});
});
Run Code Online (Sandbox Code Playgroud)