当前位置:网站首页>牛客 JS3 分隔符
牛客 JS3 分隔符
2022-07-02 17:23: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>
边栏推荐
- 2322. Remove the minimum fraction of edges from the tree (XOR and & Simulation)
- Ap和F107数据来源及处理
- linux安装postgresql + patroni 集群问题
- uniapp H5页面调用微信支付
- Vscode setting delete line shortcut [easy to understand]
- 一年頂十年
- AP and F107 data sources and processing
- Use of openpose
- Does digicert SSL certificate support Chinese domain name application?
- 智能垃圾桶(五)——点亮OLED
猜你喜欢
[shutter] dart data type (dynamic data type)
Use of openpose
关于我
寒门再出贵子:江西穷县考出了省状元,做对了什么?
移动应用性能工具探索之路
福元医药上交所上市:市值105亿 胡柏藩身价超40亿
13、Darknet YOLO3
剑指 Offer 21. 调整数组顺序使奇数位于偶数前面
Win10 system uses pip to install juypter notebook process record (installed on a disk other than the system disk)
【Leetcode】13. 罗马数字转整数
随机推荐
Explanation of traceroute command
ceph 原理
Flutter: 动作反馈
Seven charts, learn to do valuable business analysis
Dstat use [easy to understand]
The computer comes with software to make the background color of the picture transparent (matting white background)
How to quickly distinguish controlled components from uncontrolled components?
Qstype implementation of self drawing interface project practice (II)
七张图,学会做有价值的经营分析
社交元宇宙平台Soul冲刺港股:年营收12.8亿 腾讯是股东
剑指 Offer 21. 调整数组顺序使奇数位于偶数前面
Vscode setting delete line shortcut [easy to understand]
【征文活动】亲爱的开发者,RT-Thread社区喊你投稿啦
What is agile development process
剑指 Offer 25. 合并两个排序的链表
Leetcode question brushing record | 933_ Recent requests
超卓航科上市:募资9亿市值超60亿 成襄阳首家科创板企业
LeetCode:1380. Lucky number in matrix -- simple
Dgraph: large scale dynamic graph dataset
Amazon cloud technology community builder application window opens