[英]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.