工具函数

1、数组去重

原理:利用Js中对象的属性名不可重复的特点对数组进行去重操作

若有数组:

1
arr = ['a','v','a','b','e','b','w','x']
1
2
3
4
5
6
<script>
var object = {};
for(var key in arr)
if(!object[arr[key]])
object[arr[key]] = 1;
</script>

打印结果:

1
2
3
4
5
6
7
Object
a: 1
b: 1
e: 1
v: 1
w: 1
x: 1

此时object对象中的属性名便是去重后的结果。

2、在字符串中找到所有的字符 o,并返回其下标

若有字符串

1
var s = 'oresdfrgosdfsdo'
1
2
3
4
5
6
7
8
9
 <script>  
var index = -1;
while(true){
index = s.indexOf("o",index+1)
if(index == -1)
break;
console.log(index);
}
</script>

结果:

1
2
3
0
8
14



2019 年 10 月 24 日 更新

3、返回给定参数的数据类型

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* getType
* @description 返回给定参数的数据类型
* @param {Any} 需要做类型检测的参数
* @return {String}
*/
function getType(args){
if (typeof arg === 'number' && isNaN(arg)) return 'NaN';
let reg = /\s(\w{1,})\]$/g;
let str = Object.prototype.toString.call(args);
let type = reg.exec(str)[1];
return type
}

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var a = 1;
var b = false;
var c = 'ss';
var d;
var e = null;
var f = NaN;
var g = {};
var h = () => {}
var i = [];

console.log(checkType(a));
console.log(checkType(b));
console.log(checkType(c));
console.log(checkType(d));
console.log(checkType(e));
console.log(checkType(f));
console.log(checkType(g));
console.log(checkType(h));
console.log(checkType(i));

4、什么时候 val === 1 && val === 2 && val === 3 为 true?

1
2
3
4
5
6
7
8
9
10
var i= 0;
Object.defineProperty(window,'val',{
get:function(){
return ++i;
},
set:function(){
console.log('set')
}
})
console.log(val === 1 && val === 2 && val === 3);

5、计算一段文本的宽度

React

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* @name: text-width ;
* @author: admin ;
* @description: 获取字符串宽度 ;
* */
import memoize from 'lodash/memoize';

export default memoize((text, fontSize, options) => {
const {fontFamily, fontWeight} = Object.assign({fontFamily: 'Arial', fontWeight: 'normal'}, options);
const canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d');
ctx.font = `${fontSize} ${fontFamily} ${fontWeight}`;
return ctx.measureText(text).width;
}, (text, fontSize, options) => {
const obj = Object.assign({}, options, {text, fontSize});
return Object.keys(obj).map((key) => `${key}-${obj[key]}`).join(',');
});

最后更新: 2019年11月12日 20:10

原始链接: https://HowlCN1997.github.io/2019/08/24/工具函数记录/

× 请我吃糖~
打赏二维码