创建函数正常数字格式? [英] Create function normal number formatting?

查看:43
本文介绍了创建函数正常数字格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了以下代码,但 不起作用 触发错误:

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'))

推荐答案

DEMO

reverseArray.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆