初次接触JavaScript,记一次完成作业,也可以输入数字后转换
<script>
// var num = parseInt(window.prompt('input'));
function randm(lis) {
return lis[Math.round(Math.random() * (lis.length - 1))];
}
var lis = [10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000];
var num = Math.floor((Math.random()*9+1)*randm(lis));
var dataFrist = ['', '拾', '佰', '仟', '萬', '拾', '佰', '仟', '亿', '拾'];
var dataThred = ['', '拾', '佰', '仟', '萬', '拾萬', '佰萬', '仟萬', '亿', '拾亿'];
var dataSecond = ['', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖', '拾'];
var str = num.toString();
document.write(num);
function calculate() {
if (str.length > 10) {
document.write('请输入10位以内数字');
return;
}
for (i = 0; i < str.length; i++) {
var numb = dataSecond[Number(str[i])];
if (Number(str[i]) > 0 && Number(str[i + 1]) > 0) {
var unit = dataFrist[str.length - i - 1];
} else if (Number(str[i]) > 0 && Number(str[i + 1]) === 0) {
var unit = dataThred[str.length - i - 1]
} else if (Number(str[i]) === 0 && Number(str[i + 1]) === 0) {
var numb = '';
var unit = '';
} else if (Number(str[i]) === 0 && Number(str[i + 1]) > 0 && i !== str.length - 1) {
var unit = '零';
}
if (i < str.length - 1) {
console.log(numb + ' ' + unit + ' ' + i);
document.write(numb + unit);
} else {
console.log(numb + ' ' + '元整' + ' ' + i);
document.write(numb + '元整');
}
}
}
calculate();
</script>