问题:实现函数readInt(Number? num) ,如输入‘123’,输出‘一百二十三’
?
分析:1.将原字符串切割,可以用先转换为字符串后调用split()方法,或者分别对?? 10000,1000,100,10取余取得每位数;
2.将每一位分别转换为汉字;
3.插入单位;
4.去掉多余的零;
?
function readInt(num){ var src = num.toString().split(""), units = ["十","百","千","万"], curUnits = [], tmp = [], //保存转换的汉字 ret = [], i = 0, len = src.length; for(; i<len; ++i){ tmp.push("零一二三四五六七八九".charAt(src[i])); //用字符串的charAt()方法,将阿拉伯数字对应的汉字push进数组 } curUnits = units.splice(0,len-1).reverse(); //当前需要用到的单位 function joint(len){ //从十位数向高位拼接汉字与单位 if(len>0){ ret.push(tmp[len-1]); if(len>1){ //确保最高位之前没有单位 ret.push(curUnits[len-1-1]); //curUints.length = len-1; } --len; arguments.callee(len); //递归 } return ret; // ret = ["零","十","三","百","零","千","二","万","一"]; } return joint(len).reverse().join("").replace(/零+[千,百,十]/g,"零").replace(/零{1,3}/g,"零").replace(/零+$/g,""); //反转ret后,调用join()方法转化为字符串,去掉多余的零 } var a = 12030, b = 80000, c = 90101; readInt(a); //"一万二千零三十" readInt(b); //"八万" readInt(c); //"九万零一百零一"