xlearns / myblog

1 stars 0 forks source link

thinking #330

Open xlearns opened 12 months ago

xlearns commented 12 months ago

什么是工程师,什么是架构师

如何判断两个数组是否相等

function arraysAreEqual(arr1, arr2) {
  // 比较数组长度
  if (arr1.length !== arr2.length) {
    return false;
  }

  // 比较数组元素
  return arr1.every((element, index) => element === arr2[index]);
}

// 示例用法
const array1 = [1, 2, 3];
const array2 = [1, 2, 3];
const array3 = [1, 2, 4];

console.log(arraysAreEqual(array1, array2)); // 输出: true
console.log(arraysAreEqual(array1, array3)); 输出: false

如何判断两个对象是否相等

const objEqual = (obj1, obj2) => {
  const keysArr1 = Object.keys(obj1);
  const keysArr2 = Object.keys(obj2);
  if (keysArr1.length !== keysArr2.length) return false;
  else if (keysArr1.length === 0 && keysArr2.length === 0) return true;
  /* eslint-disable-next-line */ else return !keysArr1.some((key) => obj1[key] != obj2[key]);
};

Array2Tree

Tree2Array

Flat2Nested

Nested2Flat

function flattenData(data, parent = null) {
  let result = [];

  if (data.id) {
    result.push({ id: data.id, parent });
  }

  if (data.children && data.children.length > 0) {
    for (let child of data.children) {
      result = result.concat(flattenData(child, data.id));
    }
  }

  return result;
}

const input = {
  id: 1,
  children: [
    {
      id: 11,
      children: [
        {
          id: 111
        }
      ]
    },
    {
      id: 12
    }
  ]
};

const output = flattenData(input);
console.log(output);

Tree Crud

拦截String

String.prototype.fn = function(){
   return this.toString()
}

拦截Array

Array.prototype.fn = function(){
   return this
}

拦截Class

ClassName.prototype.fn = function(){
   return xx
}

对一颗Tree进行CRUD操作

框架

什么是组件