Discuss / JavaScript / 将字符串转发Nuber,为什么我的结果type是string,而不是number

将字符串转发Nuber,为什么我的结果type是string,而不是number

Topic source

function string2int(s) {

    let arrM = s.split("");

    return arrM.reduce(function (x, y) {

        return x * 10 + y * 1;

    });

}

console.log(typeof(string2int('0'))); // 结果是string,为什么不是number ?

我去问chatgpt,它也说输出类型是number……(ˉ▽ˉ;)...

标题写错了,留言没法修改吗,好像也不删除……╮(╯▽╰)╭

廖雪峰

#3 Created at ... [Delete] [Delete and Lock User]

有问题先怀疑自己的代码不对

老男孩

#4 Created at ... [Delete] [Delete and Lock User]

function string2int(s) {

    let arrM = s.split("");

    if (arrM.length===0) {

        return Nan;

    }

    if (arrM.length===1){

        return arrM[0]*1;

    }

    return arrM.reduce(function (x, y) {

        return x * 10 + y * 1;

    });

}

#5 Created at ... [Delete] [Delete and Lock User]

因为当只传入一个参数到reduc时,

arrM.reduce(function (x, y) {

        return x * 10 + y * 1;

    });这条语句是没有效果的,代码加个参数就好了

return arrM.reduce(function (x, y) {

        return x * 10 + y * 1;

    },0);

好像是这样的,谢谢! (●'◡'●)


  • 1

Reply