javascript - 这个函数有多少种简化方式?
问题描述
我正在尝试简化/概括一个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 ] ]
解决方案
下面的重写比原来的帖子更有效率。
let arr = [
[2, null, 2, null],
[2, null, 2, null],
[null, null, null, null],
[null, null, null, null]
];
function foo_four(arr) {
for (let y = 0, yl = arr.length - 1; y < yl; y++) {
let currRow = arr[y];
let nextRow = arr[y + 1];
for (let x = 0, xl = nextRow.length - 1; x < xl; x++) {
let currValue = currRow[x];
if (currValue && currValue === nextRow[x]) {
currRow[x] = currValue * 2;
nextRow[x] = null;
}
}
}
}
foo_four(arr);
console.log(arr);
// [
// [4, null, 4, null],
// [null, null, null, null],
// [null, null, null, null],
// [null, null, null, null]
// ];
推荐阅读
- python-3.x - 在 python 中遍历文件夹时遇到一些问题
- javascript - Javascript 测试引用相同的对象数组,即使我在每次测试之前都将其清空
- google-maps - 如何使用 google place API 仅获取没有国家/地区的城市名称
- sql - Postgresql中根据条件获取上一条记录
- node.js - 护照认证后无法获取任何视图
- python-3.x - 基于匹配的 XML 删除标签
- javascript - 如何从解析服务器获取父母及其孩子的条目?
- microsoft-cognitive - 将人脸数据从一个人组复制到另一个人组
- ruby-on-rails - 为 Ruby 应用程序迁移 Azure 数据库的问题
- scala - 这段带有嵌套期货的代码会造成死锁吗?