3

1、检测{[]}()是否闭合正确

考点:进栈出栈

function matchStr(str) {
    const strAray = str.split('');
    let stack = [];
    const match={
        '{':'}',
        '(':')',
        '[':']',
    };
    for (var i = 0; i < strAray.length; i++) {
        if (['{', '[', '('].includes(strAray[i])) {
            stack.push(strAray[i])
        } else {
            if(match[stack.pop()]!==strAray[i]){
                return false
            }
        }
    }
    return true
}

2、实现以下方法

f(1,2,3,4,5) => 15
f(1)(2)(3,4,5) => 15
f(1)(2)(3,4,5) => 15
f(1,2)(3,4,5) => 15
f(1)(2)(3)(4)(5) => 15

考点:函数柯里化

// 函数科利华
function foo(a, b) {
    console.log(a + b)
}

var bar = foo.bind(null, 2);
bar(3) // 5
// 实现
function fadd(...args) {
  console.log('fadd args:',args)
  return args.reduce((a, b) => a + b)
}

let len = 5;
function fn(...args) {
  console.log('fn args:' , args)
  if (args.length >= len) {
    return fadd.call(null, ...args);
  } else {
    return fn.bind(null,...args)
  }
}
fn(1)(2)(3)(4,5)

看打印结果,说明参数每次都在累加

fn args: Array [ 1 ]
fn args: Array [ 1, 2 ]
fn args: Array(3) [ 1, 2, 3 ]
fn args: Array(5) [ 1, 2, 3, 4, 5 ]
fadd args: Array(5) [ 1, 2, 3, 4, 5 ]

3、深拷贝

考点:递归

// 深拷贝
var obj = {
    a: { a1: '122', a2: 123 },
    b: { b1: new Date(), b2: function () { console.log('b2') } },
    c: { c1: /\d+/, c2: true, c3: false },
    d: { d1: Symbol(1), d2: null, d3: undefined }
}

function deepClone(obj) {
    if (typeof obj !== 'object') return obj;
    if (obj === null) return null;
    if (obj.constructor === Date) return new Date(obj);
    if (obj.constructor === RegExp) return new RegExp(obj);
    var newObj = new obj.constructor();
    for (var key in obj) {  // 会遍历原型   x in obj 原型数据也是true
        if (obj.hasOwnProperty(key)) {
            if (typeof obj[key] !== 'object') {
                newObj[key] = obj[key];
            } else {
                newObj[key] = deepClone(obj[key])
            }
        }
    }
    return newObj;
}

4、实现方法

if (a == 1 && a == 2 && a == 3) {
    console.log('ok')
}
// 方法1
var a = {
    i: 0,
    toString() {
        return ++this.i
    }
}

// 方法2
var b = 0;
Object.defineProperty(window, 'a', {
    get: () => {
        b++;
        return b;
    }
});

// 方法3
var a = [1, 2, 3];
a.toString = a.shift

5、数据扁平化

// 数组扁平化
const x = [1, 2, 3, [4, 5, [6, 7]]];

// method1
const y = x.flat(Infinity);

// method2
const z = x.toString().split(',');
const z1 = JSON.stringify(x).replace(/[\[\]]/g, '').split(',');

// method3
function flat(x) {
    if (!Array.isArray(x)) return x;
    const y = [];
    for (let i = 0; i < x.length; i++) {
        if (Array.isArray(x[i])) {
            y.push(...flat(x[i]))
        } else {
            y.push(x[i])
        }
    }
    return y;
}

6、一个整数,计算所有连续数之和

考点:二分算法

function calc(num) {
    const max = Math.ceil(num / 2);
    // 1 ~ num-1
    function plus(x, y) {
        if (y > num) {
            return ['error']
        }
        if (y == num) {
            return [x];
        }
        return [x].concat(plus(x + 1, x + 1 + y))
    }
    let arr = [];
    for (var i = 1; i <= max; i++) {
        const res = plus(i, i);
        if (res[res.length - 1] !== 'error') {
            arr.push(res)
        }
    }
    return arr;
}

7、将数组转化成树形

var menu_list = [
  {
    id: '1',
    menu_name: '设置',
    menu_url: 'setting',
    parent_id: 0
  }, {
    id: '1-1',
    menu_name: '权限设置',
    menu_url: 'setting.permission',
    parent_id: '1'
  }, {
    id: '1-1-1',
    menu_name: '用户管理列表',
    menu_url: 'setting.permission.user_list',
    parent_id: '1-1'
  }, {
    id: '1-1-2',
    menu_name: '用户管理新增',
    menu_url: 'setting.permission.user_add',
    parent_id: '1-1'
  },
]
function TransTree(arr, parentId) {
  const map = new Map();
  arr.forEach(item => {
    const parentIdArr = map.get(item.parent_id) || []
    parentIdArr.push(item)
    map.set(item.parent_id, parentIdArr)
  });
  const mapMap = (parent_id) => {
    const currArr = map.get(parent_id) || [];
    currArr.forEach(item => {
      item.children = mapMap(item.id)
    });
    return currArr
  }
  return mapMap(parentId)
}

8、红绿黄灯:1s后红灯亮,然后再隔2s绿灯亮,再隔3s黄灯亮,再隔1s红灯亮,依次循环

let arr = ['red', 'green', 'yellow'];
let i = 0;
let baseDate = Date.now()
function circle() {
  setTimeout(() => {
    console.log(arr[i], (Date.now() - baseDate) / 1000)
    if (i === 2) {
      i = 0;
    } else {
      i++
    }
    circle()
  }, (i + 1) * 1000)
}

9. 后续再描述

/**
 * @param {number} n
 * @return {string[]}
 */
var generateParenthesis = function (n) {
  const arr = []
  const fn = (str, left, right) => {
    if (left === n && right === n) {
      arr.push(str);
      return;
    }

    if (left === n) {
      const add = new Array(n - right).fill(')').join('')
      fn(str + add, n, n)
    } else if (left === right) {
      fn(str += '(', left + 1, right)
    } else {
      fn(str + '(', left + 1, right)
      fn(str + ')', left, right + 1)
    }
  }
  fn('', 0, 0)
};
//不超过总重量的情况下 最多放多少个
const total = 20;
let max = 0;
const strArr = [5, 10, 2, 11]
const fn = (hv, x, newArr) => {
  const currArr = strArr.filter(val => {
    return newArr.indexOf(Number(val)) === -1;
  })
  if (currArr.length === 0) {
    if (hv <= total) {
      max = x > max ? x : max
    } else {
      max = x - 1 > max ? x - 1 : max;
    }
    return;
  }
  for (let i = 0; i < currArr.length; i++) {
    const num = Number(currArr[i]);
    if (newArr.indexOf(num) > -1) {
      continue;
    } else if (hv < total) {
      newArr.push(num)
      fn(hv + num, x + 1, newArr)
    } else {
      max = x - 1 > max ? x - 1 : max;
      break;
    }
  }
}
fn(0, 0, [])
console.log(max)

其它

另外还有一些排序算法和数据去重算法
常见前端排序方式对比
数组去重的各种方法速度对比


lihaixing
463 声望719 粉丝

前端就爱瞎折腾