如何在javascript中创建看起来像点符号的自定义函数?例如str.getFirstIndex();

How to create custom function in javascript that looks like a dot notation? e.g., str.getFirstIndex();

本文关键字:例如 自定义函数 str getFirstIndex 符号 javascript 创建 看起来      更新时间:2024-01-03

我在查看团队项目的代码,想知道是否可以让它变得更好,"干净易懂"

我做了一项研究,但没有找到,也许是因为我不知道使用的术语?

无论如何,这是代码:

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以接受枯萎的NumberString

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