functionreduce(arr, fn, initialValue){if(arr.length ===0)return initialValue
let hasInitialValue = initialValue !==undefinedlet index, res
if(hasInitialValue){
index =0
res = initialValue
}else{
index =1
res = arr[0]}for(; index < arr.length; index++){
res =fn(res, arr[index], index, arr)}return res
}
实现一个深拷贝 针对需要拷贝的值再进行一次拷贝
functiondeepClone(data){let needCopy = Array.isArray(data)||(data &&typeof data ==='object')if(!needCopy)return data
let _data =nullif(Array.isArray(data)){
_data = data.reduce((total, cur)=>{
total.push(deepClone(cur))return total
},[])}else{
_data = Object.keys(data).reduce((total, cur)=>{
total[cur]=deepClone(data[cur])return total
},{})}return _data
}
实现一个可以循环引用的深拷贝 如果内容被拷贝过就直接返回,不拷贝了
functiondeepClone(data){const caches =[]// 拷贝的内容缓存一下return_deepClone(data)function_deepClone(data){let needCopy = Array.isArray(data)||(data &&typeof data ==='object')if(!needCopy)return data
if(caches.includes(data))return data // 检查是否被拷贝过
caches.push(data)let _data =nullif(Array.isArray(data)){
_data = data.reduce((total, cur)=>{
total.push(_deepClone(cur))return total
},[])}else{
_data = Object.keys(data).reduce((total, cur)=>{
total[cur]=_deepClone(data[cur])return total
},{})}return _data
}}
力扣题目链接
列转行
SELECT product_id, store1 store, store1 price FROM products WHERE store1 IS NOT NULL
UNION
SELECT product_id, store2 store, store2 price FROM products WHERE store2 IS NOT NULL
UNION
SELECT product_id, store3 store, store3 price FROM p…