[英]Looks like you're passing an inline function for 'component' prop for the screen 'Add' (e.g. component={() => <SomeComponent />})
[英]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作为参数来访问ThortMoney,但是如何通过执行像函数这样的点符号来访问ThortMoney?
例如,num.toShortMoney(); //返回$ 10k
如果您希望此方法可用于任何数字对象,则必须将该方法添加到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
以接受toShortMoney
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.