5. 数组降维
二维数组
let arr = [ [1], [2], [3] ]
arr = Array.prototype.concat.apply([], arr); // [1, 2, 3]
let arr = [1, 2, [3], [[4]]]
arr = arr.flat(3) // [1, 2, 3, 4]
function deepClone() {
return JSON.parse(JSON.stringify(obj))
}
function deepClone(obj) {
function isClass(o) {
if (o === null) return "Null";
if (o === undefined) return "Undefined";
return Object.prototype.toString.call(o).slice(8, -1);
}
var result;
var oClass = isClass(obj);
if (oClass === "Object") {
result = {};
} else if (oClass === "Array") {
result = [];
} else {
return obj;
}
for (var key in obj) {
var copy = obj[key];
if (isClass(copy) == "Object") {
result[key] = arguments.callee(copy);//递归调用
} else if (isClass(copy) == "Array") {
result[key] = arguments.callee(copy);
} else {
result[key] = obj[key];
}
}
return result;
}
function debounce(func, wait) {
let timeout;
return function () {
let context = this;
let args = arguments;
if (timeout) clearTimeout(timeout);
timeout = setTimeout(() => {
func.apply(context, args)
}, wait);
}
}
function throttle(func, wait) {
let previous = 0;
return function() {
let now = Date.now();
let context = this;
let args = arguments;
if (now - previous > wait) {
func.apply(context, args);
previous = now;
}
}
}
function smallest(array){
return Math.min.apply(Math, array);
}
function largest(array){
return Math.max.apply(Math, array);
}
smallest([0, 1, 2.2, 3.3]); // 0
largest([0, 1, 2.2, 3.3]); // 3.3
let list = [1, 2, 3, 4, 5]
Math.max(...list) // 5
Math.min(...list) // 1
function epsEqu(x,y) {
return Math.abs(x - y) < Math.pow(2, -52);
}
// 举例
0.1 + 0.2 === 0.3 // false
epsEqu(0.1 + 0.2, 0.3) // true
function epsEqu(x,y) {
return Math.abs(x - y) < Number.EPSILON;
}