常用的 function 及 Pollyfills 整理

functions

千分位

1
2
3
4
function format(num) {
num = num + '';
return num.replace(/\B(?=(?:\d{3})+(?!\d))/g, ',');
}

pollyfills

Array.prototype.slice()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Array.prototype.slicePollyfill = function() {
var start = 0,
end = this.length
if (arguments.length === 1) {
start = arguments[0]
} else if (arguments.length >= 2) {
start = arguments[0]
end = arguments[1]
} else {
return this
}
var tmp = []
for (var i = start; i < end; i++) {
tmp.push(this[i])
}
return tmp
}

Array.prototype.find()

Code

1
2
3
4
5
6
7
Array.prototype.myFind = function(fn){
for(var i = 0; i < this.length; i++) {
if (fn(this[i], i)) {
return this[i]
}
}
}

Usage

1
2
3
4
5
6
var arr = ['A', 'B', 'C']

arr.myFind(function (item, index) {
return item === 'A'
})
// output: "A"