-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path07-isInObj.js
50 lines (38 loc) · 969 Bytes
/
07-isInObj.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/**
*
*判断key是否在数组或对象中
*/
function typeOf(obj) {
return Object.prototype.toString.call(obj).replace(/\[object\s|]/g, '');
}
/**
* 判断是否是数组或类数组对象
* @param {*} obj
* @return {Boolean}
*
* @example
* isArrayLike([]) === true
* isArrayLike(arguments) === true
* isArrayLike(this.props.children) === true
*/
function isArrayLike(obj) {
const length = !!obj && 'length' in obj && obj.length;
const type = typeOf(obj);
return (
type === 'Array' ||
length === 0 ||
(typeof length === 'number' && length > 0 && length - 1 in obj)
);
}
// @private 判断key是否在数组或对象中
const _isInObj = (key, obj, isArray) =>
isArray ? obj.indexOf(key) > -1 : key in obj;
const obj = {
name: 'xiaoyi',
age: 18,
sno: '131530202'
}
const key = 'name'
const isArray = isArrayLike(obj)
const isinkey = _isInObj(key, obj, isArray)
console.log(isinkey)