如何在javascript中创建看起来像点符号的自定义函数?例如str.getFirstIndex();
How to create custom function in javascript that looks like a dot notation? e.g., str.getFirstIndex();
我在查看团队项目的代码,想知道是否可以让它变得更好,"干净易懂"。
我做了一项研究,但没有找到,也许是因为我不知道使用的术语?
无论如何,这是代码:
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作为参数来访问ShortMoney,但是我怎么能通过做一个类似点符号的函数来访问ShortMoney呢?
例如,num.toShortMoney()//返回1万美元
如果希望此方法在任何数字对象上都可用,则必须将该方法添加到Number
的原型中。
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;
};
然而,有些人觉得在原生类的原型中添加方法是不好的做法(除了polyfilling)。。但我想说的是,图书馆项目大多都是这样。
祝好运
您可以在toShortMoney
中将num
调整为this
,也可以扩展String.prototype
以接受枯萎的Number
或String
function toShortMoney() {
var thousand = Math.pow(10, 3),
million = Math.pow(10, 6),
billion = Math.pow(10, 9),
negative = false,
money = '0',
str = '';
num = this;
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;
}
String.prototype.toShortMoney = Number.prototype.toShortMoney = toShortMoney
相关文章:
- 自定义函数中的光标位置
- Google Sheet自定义函数返回0
- 其中是自定义函数中的属性
- 创建自定义函数以在函数上运行完整的多选下拉列表
- Google Sheets自定义函数条件格式
- dalek回调或自定义函数
- UI网格:如何从自定义函数访问MODEL_COL_FIELD
- 评估作为参数传递给 Google 电子表格中自定义函数的条件
- 具有自定义函数调用的 HTML 表单
- 使用 jQuery 对动态创建的元素调用自定义函数
- 从自定义函数返回promise
- extjs-使用传递的参数创建自定义函数
- AngularJS DI用于自定义函数
- Javascript 自定义函数错误
- 如何使用Angular 1.5组件将属性求值为字符串,这是一个自定义函数
- 为谷歌工作表创建一个自定义函数
- Angular2 在创建 ngSwitch 新视图后调用自定义函数
- JavaScript自定义函数返回意外值
- 如何在javascript中创建看起来像点符号的自定义函数?例如str.getFirstIndex();
- 调用插件外部的自定义函数并传递参数