每日前端手写题--day14

以下题目来自掘金等其它博客,但是问题的答案都是根据笔者自己的理解做出的。如果你最近想要换工作或者巩固一下自己的前端知识基础,不妨和我一起参与到每日刷题的过程中来,如何?

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

  1. 写一个函数,实现多层嵌套的数字数组求和
  2. 写一个函数,实现对函数的乱序排列
  3. 写一个函数,实现sleep功能

下面是我的一些理解:

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

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

  • 使用递归:递归函数的构建过程为:先假设数组中没有嵌套数组,使用遍历的方式求出数组的元素之和->然后增加处理嵌套数组元素的分支逻辑(递归调用本函数即可)
  • 利用特点:针对此数组元素只有可能是数字的特性,将其先转成字符串toString,然后去掉字符串中所有的[或者],最后使用split还原成数组,遍历然后相加即可
js 复制代码
// 递归的做法
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即可!
js 复制代码
// 使用sort方法
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
js 复制代码
// 异步
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();
相关推荐
水獭比特1 分钟前
工具都批准了,为什么还不能执行?给 Agent 补上第二道校验
javascript·人工智能·node.js
Simon_He8 分钟前
一个渲染内核,五个框架包:我的流式 Markdown 渲染库是怎么长成“全家桶”的
前端·vue.js·markdown
小满zs27 分钟前
关于HBuilderX+ 微信小程序开发工具启动的问题
前端·uni-app
林深见鹿_海蓝见鲸34 分钟前
微信小程序反编译完整教程(Windows 新手版)
前端
夏雪coding41 分钟前
JeecgBoot 动态路由踩坑(Vue2):刷新白屏、permissionList[0] 报 undefined,以及我最后为什么全删了
javascript·vue.js
吴声子夜歌44 分钟前
Java面试——设计模式(一)
java·设计模式·面试
默_笙1 小时前
😋 我让爬虫终于看到了我的网站,后端同事说"这也行?"(上):SEO 与渲染模式
前端·javascript
feixing_fx1 小时前
告别枯燥字体:Web 字体加载策略与 font-display 最佳实践
前端·css·前端框架·交互·css3
Liora_Yvonne2 小时前
不懂后端,只会 TypeScript,想独立做完整项目?这套全栈底座就是给前端准备的
前端·后端·全栈
前端Hardy2 小时前
GitHub 爆火!236K+ Star!一套 Skills 让 AI 按工程师方式写代码
前端·后端