深拷贝
只有对象可以利用序列化和反序列化
let obj = {
a: {
c: /a/,
d: undefined,
b: null
},
b: function () {
console.log(this.a)
},
c: [
{
a: 'c',
b: /b/,
c: undefined
},
'a',
3
]
}
//JSON无法对 undefined , function, RegExp 进行深拷贝
//利用递归
function deepClone(target){
let result;
if(typeof target=='object'){
if(Array.isArray(target)){
result=[];
for(let i in target){
result.push(deepClone(target[i]))
}
}else if(target === null){
result=null;
}else if(target.constructor===RegExp){
result=target;
}else{
result={}
for(let i in target){
result[i]=deepClone(target[i])
}
}
}else{
result=target;
}
return result;
}
new
//new一个构造函数,如果没有返回值默认返回this,如果返回值是该对象就会返回对象
function mynew(fun,...args){
if (typeof fun !== 'function') {
throw '第一个参数必须是方法';
}
let obj = Object.create(fun.prototype)
//也可以这样写:
// let obj = {};
// obj.__proto__=fun.prototype;
let result = fun.apply(obj,args)
//更改this指向,
const isObj = typeof result==='object'&&result!==null;
// const isFun = typeof result ==='function';
// return isObj?result:obj;
return isObj?result:obj;
}
function Person(name) {
this.name = name;
// return function() { // 用来测试第 5 点
// console.log('返回引用数据类型');
// };
return{
name:'zhangsan'
}
}
// 用来测试第 2 点和第 3 点
Person.prototype.sayName = function() {
console.log(`My name is ${this.name}`);
}
let mea = mynew(Person, 'jsliang'); // 用来测试第 4 点
// mea.sayName(); // My name is jsliang
console.log(mea.name); // Person {name: 'jsliang'}
数组扁平化
方法一 适用于数字
function flatten(arr) {
return arr.toString().split(',').map(function(item) {
return Number(item);//+item 利用箭头函数更加简洁
})
}
方法二 利用some+展开运算符
function flatt(arr){
let result=[]
while(arr.some(item=>Array.isArray(item))){
arr = [].concat(...arr)
console.log(arr);
}
return arr;
}