我正在尝试简化/概括一个函数 foo_one
遍历多维数组并将第一个子数组元素之外的所有子数组元素设置为 null
值。
我只得到了第一个函数,然后我应该找到更多方法来概括它,以仍然实现 foo_one
的预期目的.
如有任何建议,我们将不胜感激。
我已经实现了该函数的另外 2 个变体,如果可能的话,我希望实现更多变体。
var arr = [
[2, null, 2, null],
[2, null, 2, null],
[null, null, null, null],
[null, null, null, null]
];
function foo_one() {
for (let y = 0; y < arr.length - 1; y++) {
for (let x = 0; x < arr.length - 1; x++) {
if (arr[x + 1][y] != null) {
if (arr[x + 1][y] == arr[x][y]) {
arr[x][y] = arr[x][y] * 2;
arr[x + 1][y] = null;
}
if (arr[x][y] == null) {
arr[x][y] = arr[x + 1][y];
arr[x + 1][y] = null;
}
}
}
}
}
function foo_two() {
for (let y = 0; y < arr.length - 1; y++) {
for (let x = 0; x < arr.length - 1; x++) {
if (arr[x + 1][y] != null && arr[x + 1][y] == arr[x][y]) {
arr[x][y] = arr[x][y] * 2;
arr[x + 1][y] = null;
}
}
}
}
function foo_three() {
for (let y = 0; y < arr.length - 1; y++) {
for (let x = 0; x < arr[y].length - 1; x++) {
if (arr[x + 1][y] != null && arr[x + 1][y] == arr[x][y]) {
arr[x][y] = arr[x][y] * 2;
arr[x + 1][y] = null;
}
}
}
}
// Output
[ [ 4, null, 4, null ],
[ null, null, null, null ],
[ null, null, null, null ],
[ null, null, null, null ] ]
最佳答案
function foo_four(arr) {
let yLoopCount = arr.length - 1,
xArrLength = 0,
currentRowValue = 0,
nextRowValue = 0;
for (let y = 0; y < yLoopCount; y++) {
xArrLength = arr[y].length; // arr[y].length - 1
for (let x = 0; x < xArrLength; x++) {
currentRowValue = arr[y][x];
nextRowValue = arr[y+1][x];
if (currentRowValue && currentRowValue == nextRowValue) {
arr[y][x] = currentRowValue * 2;
arr[y+1][x] = null;
}
}
return arr;
}
var arr = [
[2, null, 2, null],
[2, null, 2, null],
[null, null, null, null],
[null, null, null, null]
];
foo_four();
// Output
// [
// [4, null, 4, null],
// [null, null, null, null],
// [null, null, null, null],
// [null, null, null, null]
// ];
a) 我也在循环最后一行。
b) 如果您在循环之外创建变量,然后重用它们,这是一个小的优化。
c) 如果您使用变量来缩短任何类型的深度引用,那么这是一个较小的优化。深入研究每个子属性需要时间,例如多次引用 arr[y][x]
而不是 currentRowValue
。
d) 我更喜欢将数组作为参数发送,并返回它,即使我更改了数组。我书中的代码更清晰,更容易调试。
e) 使用变量(或方法)名称来解释发生的情况。
f) 通过使用变量,更容易调试。
g) 我通常给所有变量一个起始值来描述它们的类型(空数组、对象、数字、字符串),这样下一个人就可以查看它们并了解它们是什么,而无需读取和处理变量的内容名字的含义。
关于javascript - 这个函数可以通过多少种方式简化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55555847/