当前位置:网站首页>牛客 JS3 分隔符
牛客 JS3 分隔符
2022-07-02 14:51:00 【淹死的鱼u】
描述
请补全JavaScript代码,要求返回参数数字的千分位分隔符字符串。
示例1
输入:
_comma(12300)
输出:
‘12,300’
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8>
</head>
<body>
<script type="text/javascript">
function _comma(number) {
// 补全代码
// 负数判断
let complex = false
let newStr = ''
if (number < 0) {
complex = true
}
str = number.toString()
// 分割字符串,返回字符串数组 ['1', '2', '3', '4', '5', '6', '7']
var arr = str.split('')
// 负数判断,移除-号
if (complex) {
arr.shift()
}
// 将分割后的字符串数组倒置 ['7', '6', '5', '4', '3', '2', '1']
arr.reverse()
// 从后往前,进行数组增加分割符操作 ['7', '6', '5', ',', '4', '3', '2', ',' ,'1']
for (let i = arr.length; i >= 0; i--) {
if ( i % 3 === 0 && i !== 0 ) {
arr.splice( i, 0, ',' )
}
}
// 将分割后的字符串数组倒置 ['1', ',', '2', '3', '4', ',', '5', '6', '7']
arr.reverse()
// 特殊情况判断,当数组首位为','时,移除
if (arr[0] === ',') {
arr.shift()
}
arr.map((item) => {
newStr += item })
// 负数判断,添加-号
if (complex) {
return '-' + newStr.toString()
} else {
return newStr.toString()
}
}
const num = _comma(1234567)
console.log(num)
</script>
</body>
</html>
边栏推荐
- Chapter 3 of hands on deep learning - (1) linear regression is realized from scratch_ Learning thinking and exercise answers
- 智能垃圾桶(五)——点亮OLED
- 2322. Remove the minimum fraction of edges from the tree (XOR and & Simulation)
- IP地址转换地址段
- 【Leetcode】14. 最长公共前缀
- QStyle实现自绘界面项目实战(二)
- Nexus簡介及小白使用IDEA打包上傳到Nexus3私服詳細教程
- Explanation of traceroute command
- Visibilitychange – refresh the page data when the specified tab is visible
- Role and function of uboot
猜你喜欢
七张图,学会做有价值的经营分析
TCP congestion control details | 2 background
简单线性规划问题
福元医药上交所上市:市值105亿 胡柏藩身价超40亿
智能垃圾桶(五)——点亮OLED
GeoServer:发布PostGIS数据源
QStyle实现自绘界面项目实战(二)
Sword finger offer 22 The penultimate node in the linked list
Green bamboo biological sprint Hong Kong stocks: loss of more than 500million during the year, tiger medicine and Beijing Yizhuang are shareholders
Sword finger offer 25 Merge two sorted linked lists
随机推荐
剑指 Offer 21. 调整数组顺序使奇数位于偶数前面
ETH数据集下载及相关问题
如何与博格华纳BorgWarner通过EDI传输业务数据?
IDEA2021.1 安装教程
远程办公对我们的各方面影响心得 | 社区征文
traceroute命令讲解
Role and function of uboot
Eye of depth (III) -- determinant of matrix
默认浏览器设置不了怎么办?
visibilitychange – 指定标签页可见时,刷新页面数据
Linux Installation PostgreSQL + Patroni cluster problem
一年頂十年
智能垃圾桶(五)——点亮OLED
七张图,学会做有价值的经营分析
executescalar mysql_ ExecuteScalar()
R and rstudio download and installation tutorial (super detailed)
The beginning of life
Sword finger offer 27 Image of binary tree
QStyle实现自绘界面项目实战(二)
Believe in yourself and finish the JVM interview this time