编写一个函数withUnitNum,参数为num(数字),将数字转为数组并且反序后添加单位打印出来。例如number为100时,输出[‘0个’, ‘0十’, ‘0百’]
负数处理,小数处理自己做啊,大于万的单位自己加啊
function withUnitNum(n){
var f =n < 0?1:-1
n = Math.abs(n)
unit = ['个','十','百','千','万']
z = []
while (n > 0)
{
z.push((n % 10) + unit[z.length])
n = Math.floor(n / 10)
}
return z
}
toString是先把数字变成string类型,reverse是反转比如 100 变成001
function withUnitNum(num) {
const units = ['个', '十', '百', '千', '万', '十万', '百万', '千万', '亿'];
const arr = num.toString().split('').reverse();
const result = [];
for (let i = 0; i < arr.length; i++) {
if (arr[i] !== '0') {
result.push(arr[i] + units[i]);
} else {
result.push('0' + units[i]);
}
}
return result;
}
console.log(withUnitNum(100)); // [ '1个', '0十', '0百' ]
不知道你这个问题是否已经解决, 如果还没有解决的话: