记一些小笔记

368 阅读1分钟

编程题:有一个长度为 32 的数组,如何将它转换为长度为4*8的二维数组

Array(32).fill(1).reduce((p,c,index) => (index % 8 === 0 ? p.push([c]) : p[p.length - 1].push(c)) && p, []);

输出如下:

也可以倒过来想这个问题:

const array = Array(32).fill(1);
Array(4).fill(1).map((item,index) => array.slice(index*8,(index+1)*8));

输出如下:

实现一个call方法

Function.prototype.myCall = function(context) {
  context = context || window;
  context.do = this;
  const args = [].slice.call(arguments, 1).map((v, i) => `arguments[${i + 1}]`);
  const result = eval(`context.do(${args})`);
  delete context.do;
  return result;
};

实现一个apply方法

Function.prototype.myApply = function(context, argList) {
  context = context || window;
  context.do = this;
  const args = (argList || []).map((v, i) => `argList[${i}]`);
  const result = eval(`context.do(${args})`);
  delete context.do;
  return result;
};

实现一个bind方法

Function.prototype.myBind = function(context) {
  context = context || window;
  const self = this;
  const args = [].slice.call(arguments, 1);
  return function() {
    context.do = self;
    const innerArgs = [].slice.call(arguments);
    const list = args.concat(innerArgs);
    const result = eval(
      `context.do(${args.concat(innerArgs).map((v, i) => `list[${i}]`)})`
    );
    delete context.do;
    return result;
  };
};