functionarrayToTreeRec(nodes){
const map ={
};const tree =[];for(const node of nodes){
node[node.id]={
...node,children:[]};}for(const node of Object.values(map)){
if(node.parentId ===null){
tree.push(node);}else{
map[node.parentId].children.push(node);}}return tree;}
四. 实现JSON.stringfy方法
functionjsonStringify(obj){
// 处理非对象类型,直接返回对应的字符串形式if(typeof obj !=='object'|| obj ===null){
// 处理字符串类型if(typeof obj ==='string'){
console.log(obj);return'"'+ obj +'"';}returnString(obj);}// 处理数组类型if(Array.isArray(obj)){
const result =[];for(let i =0; i < obj.length; i++){
result.push(jsonStringify(obj[i]));}return'['+ result.join(',')+']';}// 处理对象类型const result =[];for(let key in obj){
if(obj.hasOwnProperty(key)){
const value =jsonStringify(obj[key]);// 处理 undefined、函数和 symbol 属性值if(value !==undefined){
const prop ='"'+ key +'":'+ value;
result.push(prop);}}}return'{'+ result.join(',')+'}';}let obj ={
name:'zs',age:18,hobby:['1','2','3']}
console.log(jsonStringify(obj));
五. new操作符的实现
function_new(obj,...rest){
// 基于obj的原型创建一个新的对象const newObj = Object.create(obj.prototype);// 添加属性到新创建的newObj上, 并获取obj函数执行的结果.const result =obj.apply(newObj, rest);// 如果执行结果有返回值并且是一个对象, 返回执行的结果, 否则, 返回新创建的对象returntypeof result ==='object'? result : newObj;}
六. 数组去重的几种方法
两层for循环
functionunique(arr){
let len = arr.length
for(let i =0; i < len; i++){
for(let j = i +1; j < len; j++){
if(arr[i]== arr[j]){
arr.splice(j,1)
j--
len--}}}return arr
}
filter + indexOf
functionunique(arr){
return arr.filter((item, index)=>{
return arr.indexOf(item)== index
})}
创建新数组 + includes
functionunique(arr){
let newArr =[]for(let i =0; i < arr.length; i++){
if(!newArr.includes(arr[i])){
newArr.push(arr[i])}}return newArr
}
indexOf实现
functionunique(arr){
let newArr =[]for(let i =0; i < arr.length; i++){
if(newArr.indexOf(arr[i])===-1){
newArr.push(arr[i])}}return newArr
}
Set实现
functionunique(arr){
return[...newSet(arr)]}
七. 大数相加
functionadd(str1, str2){
let maxLength = Math.max(str1.length, str2.length)
str1 = str1.padStart(maxLength,0)
str2 = str2.padStart(maxLength,0)let temp =0let flag =0// 余数let result =''for(let i = maxLength -1; i >=0; i--){
temp = str1[i]+ str2[i]+ flag
flag = Math.floor(temp /10)
result = temp %10+ result
}if(flag ==1){
result ='1'+ result
}return result
}let a ="9876543210123456789000000000123";let b ="1234567898765432100000012345678901";
console.log(add(a, b));
八. 大数相乘
functionmultiplyStrings(num1, num2){
const len1 = num1.length;const len2 = num2.length;const result =newArray(len1 + len2).fill(0);// 结果数组初始化为0for(let i = len1 -1; i >=0; i--){
for(let j = len2 -1; j >=0; j--){
const product =Number(num1[i])*Number(num2[j]);// 计算当前位的乘积const sum = result[i + j +1]+ product;// 当前位的和等于之前的结果加上当前位乘积
result[i + j +1]= sum %10;// 保存当前位的数值
result[i + j]+= Math.floor(sum /10);// 进位}}// 去掉结果前面的0while(result[0]===0&& result.length >1){
result.shift();}return result.join('');// 将结果转为字符串返回}let a ="123";let b ="456";
console.log(multiplyStrings(a, b));