每日前端手写题--day14

如果你最近想要换工作或者巩固一下自己的前端知识基础,不妨和我一起参与到每日刷题的过程中来,如何?

第14天要刷的手写题如下:

  1. 写一个函数,实现多层嵌套的数字数组求和

  2. 写一个函数,实现对函数的乱序排列

  3. 写一个函数,实现sleep功能

下面是我的一些理解:

1. 写一个函数,实现多层嵌套的数字数组求和

解决这个问题的本质在于如何从嵌套着的数组中提取出元素,大概有两种思路:

  • 使用递归:递归函数的构建过程为:先假设数组中没有嵌套数组,使用遍历的方式求出数组的元素之和->然后增加处理嵌套数组元素的分支逻辑(递归调用本函数即可)

  • 利用特点:针对此数组元素只有可能是数字的特性,将其先转成字符串toString,然后去掉字符串中所有的[或者],最后使用split还原成数组,遍历然后相加即可

function addNumbers (input) {
    if(!Array.isArray(input)) return input;
    let rst = 0;
    const _arr = [...input];

    while (_arr.length) {
        const _current = _arr.pop();
            rst += Array.isArray(_current)?addNumbers(_current):_current;
    }

    return rst;
}


function addNumbersUsingString (input) {
    if(!Array.isArray(input)) throw new Error('must be an array');
    let _toString = input.toString();
    _toString = _toString.replace(/[]/g,'');
    const _toArray = _toString.split(",");
    const rst = _toArray.reduce((accu, v, i ,a)=>{
        return accu+Number(v);
    },0)


    return rst;
}

const test = [1,[[22]],3,4,[[[[6]]]]];

console.log(addNumbers(test));
console.log(addNumbersUsingString(test));

2. 写一个函数,实现对函数的乱序排列

可以使用哈希的思想也可以取巧使用Array.prototype.sort方法。

  • 生成哈希下标:使用while循环每次从原数组中弹出一个元素,弹出元素的下标是随机生成的,直到原来数组元素弹完

  • 巧用sort方法:Array.prototype.sort的入参是一个函数,这个函数的返回值决定相邻两个元素的位置,所以只需要这个函数的返回值随机是true或者false即可!

const randomSort = inputArr => inputArr.sort(() => Math.random() - 0.5);


const randomSortHash = inputArr => {
    const _rst = [];
    const _arr = [...inputArr];
    while (_arr.length) {
        const _len = _arr.length;
        const _hash = _len*Math.random() | 0;
        console.log(_hash)
        const _current = _arr.splice(_hash,1)[0];
        _rst.push(_current);
    }
    return _rst;
};


const a = [1,2,3,4,5,6,7,8,9];

console.log(randomSort(a));
console.log(randomSortHash(a));

3. 写一个函数,实现sleep功能

两种实现思路:同步的和异步的

  • 同步:使用while和时间戳

  • 异步:使用定时器和promise

const asyncSleep = gap => new Promise(res => setTimeout(res, gap*1000));


function syncSleep (gap) {
    const startTime = +new Date();
    while(+new Date() - startTime <= gap *1000){}
}


async function test () {
    console.log(+new Date());
    await asyncSleep(2);
    console.log(+new Date());
    syncSleep(2);
    console.log(+new Date());
}

test();

最后

如果你现在正在找工作,可以私信“web”进群领取前端面试小册以及更多阿里、字节大厂面试真题合集,和p8大佬一起交流。

 

  • 11
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Web面试那些事儿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值