gpt4 book ai didi

javascript - 如何将数字转换为字符串并将它们放入 JavaScript 中的数组中?

转载 作者:行者123 更新时间:2023-11-30 12:03:12 27 4
gpt4 key购买 nike

我正在用数组方法解决一个练习;我应该输入一个数字,返回值应该是相同的数字,每两个连续的偶数之间有破折号。

到目前为止,我已经编写了这段代码,但它返回一个空数组,如果您能指出我的错误,那会比提供替代解决方案要好得多。

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;
}

最佳答案

你正在比较你的 num 变量,你必须比较 prog 变量:

    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){
}

关于javascript - 如何将数字转换为字符串并将它们放入 JavaScript 中的数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36072763/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com