JS工具函数

判断数据类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 工具函数
let _toString = Object.prototype.toString
let map = {
array: 'Array',
object: 'Object',
function: 'Function',
string: 'String',
null: 'Null',
undefined: 'Undefined',
boolean: 'Boolean',
number: 'Number'
}
let getType = (item) => {
return _toString.call(item).slice(8, -1)
}
let isTypeOf = (item, type) => {
return map[type] && map[type] === getType(item)
}

数组去重方法

键值对原理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
let x = [1, 3, 4, 1, 4, 6, 9];

Array.prototype.unique = function () {
var temp = {},
arr = [],
len = this.length;
for(let i = 0; i < len; i ++){
if (!temp[this[i]]) {
temp[this[i]] = 'abc';
arr.push(this[i]);
}
}

return arr;
}

console.log(x.unique());

ES6 set

1
2
3
let arr = [1, 3, 4, 1, 4, 6, 9];
let b = [...new Set(arr)];
console.log(b); // [1, 3, 4, 6, 9]

判断是否为空

1
2
3
4
5
6
7
8
function isEmpty(value){
return (
value === undefined ||
value === null ||
(typeof value === 'object' && Object.keys(value).length===0) ||
(typeof value === 'string' && value.trim().length===0)
);
}

比较属性

不同的引用类型含有相同的属性

If they’re distinct objects, even if they contain identical properties, the comparison will result in false.

1
2
3
4
var arr1 = ['Hi!'];
var arr2 = ['Hi!'];
console.log(arr1 === arr2);
// false

If we have two distinct objects and want to see if their properties are the same, the easiest way to do so is to turn them both into strings and then compare the strings. When the equality operators are comparing primitives, they simply check if the values are the same.

1
2
3
4
var arr1str = JSON.stringify(arr1);
var arr2str = JSON.stringify(arr2);
console.log(arr1str === arr2str);
// true

Another option would be to recursively loop through the objects and make sure each of the properties are the same.