无法弄清楚为什么这个数字到单词功能不起作用

时间:2015-05-21 07:55:08

标签: javascript

我正在尝试编写一个从1-999中取任何数字并将其转换为单词(345 - >“三百四十五”等)的函数。我对Javascript很新,所以代码有点凌乱,但它适用于大于19的所有内容。任何小于或等于19的内容都会返回空白,我不能为我的生活找出原因,这让我很头疼。

function wordify(n){
	var number = n;
	function teensToWord(num){
		switch (num){
			case 10: return "ten";
			case 11: return "eleven";
			case 12: return "twelve";
			case 13: return "thirteen";
			case 14: return "fourteen";
			case 15: return "fifteen";
			case 16: return "sixteen";
			case 17: return "seventeen";
			case 18: return "eighteen";
			case 19: return "nineteen";
		}    
	}
	function toWord(digit){
		switch (digit){
			case 1: return "one";
			case 2: return "two";
			case 3: return "three";
			case 4: return "four";
			case 5: return "five";
			case 6: return "six";
			case 7: return "seven";
			case 8: return "eight";
			case 9: return "nine";
			case 0: return "";
		}

	}
	function tensToWord(digit) {
		switch (digit){
			case 2: return "twenty";
			case 3: return "thirty";
			case 4: return "forty";
			case 5: return "fifty";
			case 6: return "sixty";
			case 7: return "seventy";
			case 8: return "eighty";
			case 9: return "ninety";
			case 0: return "";
		}
	}
	function reduceOnes (num) {
		var onesPlace = num;
		if(onesPlace < 10){return onesPlace;}
		else{onesPlace -= 10;}
		return reduceOnes(onesPlace);
	}
	function reduceTens (num) {
		var tensPlace = num;
		if(tensPlace < 100){return tensPlace;}
		else{tensPlace -=100;}
		return reduceTens(tensPlace);
	}

	var numArr = [];

	var ones = reduceOnes(n);

	n = n-ones;

	var tens = reduceTens(n)/10;

	n = n - (tens*10);

	var hundreds = n/100;
	
	if(number>=10 && number<=19){
		numArr.unshift(teensToWord(number));
	}else if(number<10){
		numArr.unshift(toWord(number));
	}else{
		numArr.unshift(toWord(ones));
		if(number>=10){
			numArr.unshift(tensToWord(tens));
			if(number>=100){
				numArr.unshift(toWord(hundreds)+ " hundred");
			}
		}
	}
	
	return numArr.join(' ');
}

0 个答案:

没有答案