在日常的開發(fā)過程中假丧,經(jīng)常會碰到j(luò)avaScript原生對象方法不夠用的情況,所以經(jīng)常會對javaScript原生方法進(jìn)行擴(kuò)展破喻。下面就是在實(shí)際工作時虎谢,經(jīng)常使用的一些方法,做一下記錄曹质,有需要的可以拿去婴噩。
1、String篇
1.1羽德、字符串做相加運(yùn)算:
浮點(diǎn)數(shù)的精度問題是javaScript計(jì)算的一個障礙几莽,因?yàn)橛行┬?shù)以二進(jìn)制表示的話位數(shù)是無窮的。比如1.1宅静,在程序中無法真正的表示1.1章蚣,只能做到一定程度的準(zhǔn)確,但是無法避免精度的丟失姨夹。
String.prototype.add = function (arg2) {
let r1, r2, m
try {
r1 = this.toString().split('.')[1].length
} catch (e) {
r1 = 0
}
try {
r2 = arg2.toString().split('.')[1].length
} catch (e) {
r2 = 0
}
m = Math.pow(10, Math.max(r1, r2))
return (Math.round(this * m + arg2 * m) / m).toString()
}
1.2纤垂、字符串做相減運(yùn)算
String.prototype.reduce = function (arg2) {
let r1, r2, m
try {
r1 = this.toString().split('.')[1].length
} catch (e) {
r1 = 0
}
try {
r2 = arg2.toString().split('.')[1].length
} catch (e) {
r2 = 0
}
m = Math.pow(10, Math.max(r1, r2))
return (Math.round(this * m - arg2 * m) / m).toString()
}
2、Number篇
2.1磷账、數(shù)字做相加運(yùn)算
Number.prototype.add = function (arg2) {
let r1, r2, m
try {
r1 = this.toString().split('.')[1].length
} catch (e) {
r1 = 0
}
try {
r2 = arg2.toString().split('.')[1].length
} catch (e) {
r2 = 0
}
m = Math.pow(10, Math.max(r1, r2))
return Math.round(this * m + arg2 * m) / m
}
2.2峭沦、數(shù)字做相減運(yùn)算
Number.prototype.reduce = function (arg2) {
let r1, r2, m
try {
r1 = this.toString().split('.')[1].length
} catch (e) {
r1 = 0
}
try {
r2 = arg2.toString().split('.')[1].length
} catch (e) {
r2 = 0
}
m = Math.pow(10, Math.max(r1, r2))
return Math.round(this * m - arg2 * m) / m
}
3、Array數(shù)組篇
3.1逃糟、獲取數(shù)組最大值
Array.prototype.getMax = function () {
return Math.max.apply(null, this.map((seg) => {return +seg}))
}
3.2吼鱼、獲取數(shù)組的深拷貝值
Array.prototype.getCopy = function () {
let that = this
return JSON.parse(JSON.stringify(that))
}
3.3蓬豁、使用特殊字符(symbol)替換數(shù)組中的0
Array.prototype.replaceZero = function (symbol = '-') {
return this.map(function (seg) {
return +seg == 0 ? symbol : seg
})
}
3.4、獲取數(shù)組中指定 idx 的元素菇肃,其中 idx 若超過數(shù)組長度length地粪,則查找 idx 與 length * n 相減的序號元素
Array.prototype.getItemByIdx = function (idx = 0) {
function getArrByIdx (list, idx) {
if (list.length - 1 < idx) {
idx -= list.length
return getArrByIdx(list, idx)
} else {
return list[idx]
}
}
return getArrByIdx(this, idx)
}
3.5、獲取數(shù)組中由自定義數(shù)量的隨機(jī)元素組成的新數(shù)組琐谤。count 為所需數(shù)量
Array.prototype.getRandomArrayElements = function (count) {
var shuffled = this.slice(0),
i = this.length,
min = i - count,
temp, index
while (i-- > min) {
index = Math.floor((i + 1) * Math.random())
temp = shuffled[index]
shuffled[index] = shuffled[i]
shuffled[i] = temp
}
return shuffled.slice(min)
}
3.6蟆技、獲取數(shù)組中的隨機(jī)元素
Array.prototype.getRandomElement = function () {
let lth = this.length - 0.1
return this[Math.floor(Math.random() * lth)]
}
3.7、數(shù)組內(nèi)元素求加和
Array.prototype.sum = function () {
return eval(this.join('+'))
}