我正在尝试获取一个名为input
的数组并对其进行循环。
如果任何值是奇数,则它们会乘以 2。
如果有偶数,它们会被除以 2,然后被推送到一个输出数组,然后我可以返回该数组。
到目前为止,我已经有了这个(使用 cmd
节点):
function modify(input) {
var output = [];
for (i=0; i=input.length; i++) {
if (input % 2 == 1) {
input*2;
output.push[input];
}
if (input % 2 == 0) {
input/2;
output.push[input];
}
}
return output;
}
module.exports.modify = modify;
最佳答案
最大的问题是你永远不会访问input
的元素,而只是访问数组本身。您的 if (input % 2 == 1)
行检查数组 mod 2 是否等于 1。这没有意义,因为您实际上不能这样做数组的数学运算。
您需要对每个元素执行此操作,因此最小的更改是在循环中使用 input[i]
。
您还可以进行许多其他更改,以及一些可以使代码变得更好的惯用模式。如果您使用的是最新的浏览器并且有 forEach
或 map
,您可以使用如下结构替换循环:
var output = input.map(function (it) {
if (it % 2 == 1) return it * 2;
if (it % 2 == 0) return it / 2;
});
仍然可以清理,因为 x % 2
只能返回 0
或 1
,因此您可以替换第二个条件与 else
或假设它返回 0:
var output = input.map(function (it) {
if (it % 2 == 1) return it * 2;
return it / 2;
});
由于 JS 处理 true 和 false 的方式,特别是转换数字,您可以省略 == 1
(1
为 true),并将条件交换为三元:
var output = input.map(function (it) {
return (it % 2) ? it * 2 : it / 2;
});
由于您将其包装到函数中,如果您使用 map
,那么 output
并不是绝对必要的,因此您可以这样做:
module.exports.modify = function (input) {
return input.map(function (it) {
return (it % 2) ? it * 2 : it / 2;
});
};
如果您有 ES6 支持(可能通过 the brilliant 6to5 project ),您可以用箭头函数替换函数声明:
module.exports.modify = (input) => {
return input.map((it) => {
return (it % 2) ? it * 2 : it / 2;
});
};
如果您想真正了解它,您可以删除 return
语句(感谢箭头函数):
module.exports.modify = input => input.map(it => it % 2 ? it * 2 : it / 2);
关于javascript - 从输入修改数组然后返回输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28458249/