我的代码小片段
- 获取cookie
1
2
3
4
5
6
7
8function getCookie() {
let cookies = document.cookie;
let _cookies = cookies.split(";");
return _cookies.reduce((a, cookie) => {
let _cookie = cookie.split("=");
return Object.assign(a, { [_cookie[0]]: _cookie[1]});
}, {});
}; 深拷贝
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
38let deep_clone = function (obj) {
let clonedObj;
// Handle null or undefine or primitive type
if (obj === null || typeof obj !== 'object') {
return obj;
}
// Handle Array
if (obj instanceof Array) {
clonedObj = [];
for (let index = 0; index < obj.length; index++) {
clonedObj[index] = deep_clone(obj[index]);
}
return clonedObj;
}
// Handle Date
if (obj instanceof Date) {
clonedObj = new Date();
clonedObj.setDate(obj.getDate());
return clonedObj;
}
// Handle Object
if (obj instanceof Object) {
clonedObj = {};
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
clonedObj[key] = deep_clone(obj[key]);
}
}
return clonedObj;
}
throw new Error('cannot clone this');
}翻转数组
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// 翻转数组
function reverse(arr) {
var arr = arr || [];
if (arr.length === 0) return [];
var temp_arr = copy_array(arr);
var length = temp_arr.length;
var index = length,
new_index = 0;
while(--index >= 0) {
var value = temp_arr[index];
console.log();
arr[new_index++] = value;
}
}
// 拷贝数组
function copy_array(arr) {
if (!(arr instanceof Array)) {
throw new Error('argument is not array');
}
if (arr.length == 0) {
return []
}
var index = -1,
length = arr.length,
resIndex = 0,
result = [];
while(++index < length) {
var value = arr[index];
result[resIndex++] = value;
}
return result;
}