gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:02:02 24 4
gpt4 key购买 nike

我正在查看我们团队项目的代码,想知道我是否可以让它变得更好,“干净且易于理解”

我做了一个研究,但我找不到任何东西,也许是因为我不知道术语的使用?

这里是代码:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com