作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在查看我们团队项目的代码,想知道我是否可以让它变得更好,“干净且易于理解”。
我做了一个研究,但我找不到任何东西,也许是因为我不知道术语的使用?
这里是代码:
var num = 10000;
function toShortMoney(num) {
var thousand = Math.pow(10, 3),
million = Math.pow(10, 6),
billion = Math.pow(10, 9),
negative = false,
money = '0',
str = '';
str = num.toString();
if(str.indexOf('-') > -1) {
negative = true;
str = str.slice(1);
num = str.valueOf(str);
}
if(num < million && num >= thousand) { //thousand
num = (Math.floor(num / thousand)).toFixed(0);
money = num + 'K';
}
else if(num < billion && num >= million) { //million
num = (num / million).toFixed(2).replace(/(\.?0+$)/,'');
money = num + 'M';
}
else {
money = Math.floor(num).toFixed(0);
}
if(negative)
return '($' + money + ')';
return '$' + money;
}
最初我可以通过将变量 num 作为参数来访问 toShortMoney,但是我如何通过像函数这样的点符号来访问 toShortMoney?
e.g., num.toShortMoney(); //returns $10k
最佳答案
如果您希望此方法可用于任何数字对象,则必须将该方法添加到Number
的原型(prototype)中。
Number.prototype.toShortMoney = function() {
// in the context of being called on a number, the number will
// not be an argument, but you access it via this eg.:
return '$' + this;
};
但是,有些人觉得向 native 类的原型(prototype)添加方法是不好的做法(polyfilling 除外)。但我想说的是,对于库项目来说,大多数情况下都是如此。
祝你好运
关于javascript - 如何在看起来像点符号的 javascript 中创建自定义函数?例如,str.getFirstIndex();,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36415552/
我正在查看我们团队项目的代码,想知道我是否可以让它变得更好,“干净且易于理解”。 我做了一个研究,但我找不到任何东西,也许是因为我不知道术语的使用? 这里是代码: var num = 10000; f
我是一名优秀的程序员,十分优秀!