収集整理js常用ツール関数
1575 ワード
(更新は2018.12.15)継続更新...
整理されたいくつかのフロントエンド開発でよく使われるツール関数を収集します.
アレイの重量除去方法
配列のクイックソート
一致するID(15または18)
1つの文字列の中で最も多く現れる文字と回数を探し出します
整理されたいくつかのフロントエンド開発でよく使われるツール関数を収集します.
アレイの重量除去方法
function (arr) {
let res = []
let json = {}
for (let i = 0; i < this.length; i++) {
if (!json[this[i]]) {
res.push(this[i])
json[this[i]] = 1
}
}
return res
}
// es6
Array.from(new set(arr))
配列のクイックソート
function quickSort (arr) {
if (arr.length <= 1) {
return arr
}
let pivotIndex=Math.floor(arr.length / 2);
let pivot=arr.splice(pivotIndex, 1)[0];
let left = []
let right = []
for (let i = 0; i < arr.length; i++) {
if(arr[i] < pivot) {
left.push(arr[i])
}else{
right.push(arr[i])
}
}
return quickSort(left).concat([pivot], quickSort(right))
}
一致するID(15または18)
function isIdCardNo (num) {
num = num.toUpperCase()
// 15 18 ,15 ,18 17 , , X。
if (!(/(^/d{15}$)|(^/d{17}([0-9]|X)$)/.test(num))) {
alert(' , !/n15 ,18 X。')
return false
}
}
1つの文字列の中で最も多く現れる文字と回数を探し出します
const str = 'zheshiceshidaima!'
const obj = {}
for (let i=0; i < str.length; i++) {
let char = str.charAt(i)
if (obj[char]) {
obj[char]++
} else {
obj[char] = 1
}
}
let max = 0
let maxKey
for (let key in obj) {
if (max < obj[key]) {
max = obj[key]
maxKey = key
}
}
console.log(maxKey, max)