请实现一个js脚本,要求做到将数字转化为千分位表示

如:
10000 ----> 10,000

10000121213 ----> 10,000,121,213

今天无意中看到这道题目,想了4种解决方案,和大家分享一下:

 

//法一
function parseNum(num){
	var list = new String(num).split('').reverse();
	for(var i = 0; i < list.length; i++){
		if(i % 4 == 3){
			list.splice(i, 0, ',');
		}
	}
	return list.reverse().join('');
}

console.log(parseNum(10000121213));


//法二
function parseNum(num){
	var reg=/(?=(?!)(d{3})+$)/g;
	return String(num).replace(reg, ',');
}
console.log(parseNum(10000121213));


//法三
String.prototype.strReverse = function(){
	return this.split('').reverse().join('');
}

function parseNum(num){
	var str_num = String(num);
	var len = str_num.length;
	var tail = str_num.slice(0, len % 3);
	tail = tail.strReverse();
	var reg=/d{3}/g;
	var list = str_num.strReverse().match(reg);
	list.push(tail);
	var res = list.join(',').strReverse();
	return res;
}
console.log(parseNum(10000121213));


//法四
function parseNum(num){
	var list = String(num).split('').reverse();
	var temp = [];
	for(var i = 0, len = list.length; i < len; i = i + 3){
		temp.push(list.slice(i, i + 3).join(''));
	}
	return temp.join(',').split('').reverse().join('');
}
console.log(parseNum(10000121213));