我用数组方法解决了一个练习;我应该输入一个数字,返回的值应该是相同的数字,每两个连续的偶数之间用短划线。
到目前为止,我已经编写了这段代码但是它返回了一个空数组,如果你能指出我的错误而不是提供另一种解决方案会好得多。
function dashit(num){
//test num = 025468, expected arr = ["0","-","2","5","4","-","6","- ","8"]
var arr = [];
var prog = num.toString().split(""); // I suppose ["0","2","5","4","6","8"]
for (var i = 0; i<num.length; i = i + 2){
if (num[i] % 2 == 0 ){ // case of "0" and "2"
if (num[i+1] % 2 == 0){
arr.push(prog[i]); // "0" pushed from prog to arr
arr.push("-"); // "-" pushed from prog to arr
arr.push(prog[i+1]); // "2" pushed from prog to arr
}
}
else { // case of "5" and "4"
arr.push(prog[i]); // "5" pushed from prog to arr
arr.push(prog[i+1]); // "4" pushed from prog to arr
}
}
return arr;
}
答案 0 :(得分:2)
您正在比较num
var,您必须比较prog
var:
function dashit(num){
var prog = num.toString().split(""); // I suppose ["0","2","5","4","6","8"]
for (var i = 0; i<prog.length; i = i + 2){
if (prog[i] % 2 == 0 ){ // case of "0" and "2"
if (prog[i+1] % 2 == 0){
}
答案 1 :(得分:1)
您正在将num
作为octal
号码(从0开始)
尝试将其作为string
dashit("025468");
参见工作示例:
function dashit(num){
var arr = [];
for (var i = 0; i<num.length; i = i + 2){
if (num[i] % 2 == 0 ){ // case of "0" and "2"
if (num[i+1] % 2 == 0){
arr.push(num[i]); // "0" pushed from prog to arr
arr.push("-"); // "-" pushed from prog to arr
arr.push(num[i+1]); // "2" pushed from prog to arr
}
}
else { // case of "5" and "4"
arr.push(num[i]); // "5" pushed from prog to arr
arr.push(num[i+1]); // "4" pushed from prog to arr
arr.push("-");
}
}
return arr;
}
document.write(JSON.stringify(dashit("025468")));
答案 2 :(得分:0)
此问题非常适合使用递归。我确定你的老师想要的是什么; - )
var n = '02546878642';
var isPair = function(n1, n2) {
return Number(n1) % 2 == 0 && Number(n2) % 2 == 0;
};
var result = (function f(i, o) {
if (i.length < 1) return o;
var first = i.shift();
var next = i[0];
o.push(first);
if (isPair(first, next)) {
o.push('-');
}
return f(i, o);
})(n.split(''), []);
$('#result').html(result.join(''));
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='result'>result</div>
&#13;