创建函数正常数字格式? [英] Create function normal number formatting?
问题描述
我尝试了以下代码,但 不起作用 触发错误:
I tried the following code but is doesn't work triggers an error:
val.reverse is not a function
我该如何解决?
演示: http://jsfiddle.net/9ysZa/>
//I want this output: 1,455,000
function num(val){
var result = val.reverse().join("")
.match(/[0-9]{1,3}/g).join(",")
.match(/./g).reverse().join("");
return result
}
alert(num('1455000'))
推荐答案
reverse
是 Array.prototype
上的一个方法——它适用于数组.由于 val
是一个字符串,您需要调用 val.split('')
将其放入一个数组中.
reverse
is a method on Array.prototype
—it works with arrays. Since val
is a string, you'll need to call val.split('')
to get it into an array.
function num(val){
var result = val.split('').reverse().join("")
.match(/[0-9]{1,3}/g).join(",")
.match(/./g).reverse().join("");
return result
}
alert(num('1455000'));
提醒您正在寻找的结果.
Which alerts the results you're looking for.
编辑
根据您的评论,您似乎希望在数字 1455000 而非字符串 '1455000' 上运行此程序.如果是这样,在 split()
之前添加一个 toString
调用将起作用(并且对字符串 ** 和数字都起作用).
Based on your comment, it looks like you want to run this on the number 1455000 rather than the string '1455000'. If so, adding a toString
call before split()
will work (and will work on both strings **and numbers).
这是一个更新的小提琴
这篇关于创建函数正常数字格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!