直接上代码,只要是利用map,然后找规律
function change(str){
let res = null;
let numMap = {
'一': 1,
'二': 2,
'三': 3,
'四': 4,
'五': 5,
'六': 6,
'七': 7,
'八': 8,
'九': 9,
'十': 10,
'零': 0
};
let weiMap = {
'十': 10,
'百': 100,
'千': 1000,
}
for(let i = 0; i<str.length ; i++){
let item = str[i];
let num = numMap[item];
let afterWei = weiMap[str[i+1]];
let frontWei = weiMap[str[i-1]];
if(item === '万'){
res *= 10000;
}else if(afterWei){//后面是“位”的单位,则相乘
res += num * afterWei;
i++;
}else if(frontWei){//fix,后面没有单位,且前面有单位,如一千三
res += num * frontWei/10;
}else{//前后都没有单位,则直接相加
res += num;
}
}
return res;
}
console.log(change('一千三百二十一万一千三百二十一')) ;
console.log(change('一千三')) ;
console.log(change('一千三百零一')) ;
console.log(change('十二')) ;