翻转字符串
思路:先将字符串变成数组,再利用数组相关的处理处理函数实现最终目的。
实现:
//翻转字符串
let str = '123'
let str2 = str.split('').reverse().join('')
let str3 = [...str].reverse().join('')
let str4_arr = []
for (let i = str.length - 1; i >= 0; i--) {
str4_arr.push(str[i])
}
let str4 = str4_arr.join('')
let str5 = str.split('').reduce((pre, cur) => {
return cur + pre
}, '')
console.log(str2, str3, str4, str5)
对象深浅拷贝
实现:
function deepClone1(obj){
let newObj = Array.isArray(obj) ? [] : {}
for(let key in obj){
newObj[key] = obj[key]
}
return newObj
}
function deepClone2(obj){
return JSON.parse(JSON.stringify(obj))
}
function deepClone3(obj){
if(obj === null || typeof obj !== 'object'){
return obj
}
let newObj = Array.isArray(obj) ? [] : {}
for(let key in obj){
if(typeof obj[key] === 'object'){
newObj[key] = deepClone3(obj[key])
}else{
newObj[key] = obj[key]
}
}
return newObj
}
function deepClone4(obj){
if(obj === null || typeof obj !== 'object' || obj instanceof RegExp || obj instanceof Date){
return obj
}
let newObj = Array.isArray(obj) ? [] : {}
for(let key in obj){
newObj[key] = deepClone4(obj[key])
}
return newObj
}
function deepClone5(obj){
let newObj = Object.assign({},obj)
return newObj
}
function deepClone6(obj){
let newObj = lodash.cloneDeep(obj)
return newObj
}
function deepClone7(data, hash = new WeakMap()) {
if(typeof data !== 'object' || data === null){
throw new TypeError('传入参数不是对象')
}
// 判断传入的待拷贝对象的引用是否存在于hash中
if(hash.has(data)) {
return hash.get(data)
}
let newData = {};
const dataKeys = Object.keys(data);
dataKeys.forEach(value => {
const currentDataValue = data[value];
// 基本数据类型的值和函数直接赋值拷贝
if (typeof currentDataValue !== "object" || currentDataValue === null) {
newData[value] = currentDataValue;
} else if (Array.isArray(currentDataValue)) {
// 实现数组的深拷贝
newData[value] = [...currentDataValue];
} else if (currentDataValue instanceof Set) {
// 实现set数据的深拷贝
newData[value] = new Set([...currentDataValue]);
} else if (currentDataValue instanceof Map) {
// 实现map数据的深拷贝
newData[value] = new Map([...currentDataValue]);
} else {
// 将这个待拷贝对象的引用存于hash中
hash.set(data,data)
// 普通对象则递归赋值
newData[value] = deepClone7(currentDataValue, hash);
}
});
return newData;
}
function deepClone8(obj){
let newObj = {...obj}
return newObj
}