GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fe-notes/JavaScript/编程题.md at master · Inchill/fe-notes

Expand file tree

/

编程题.md

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
81 lines (68 loc) · 2.07 KB
/

编程题.md

Copy path

File metadata and controls

81 lines (68 loc) · 2.07 KB
Raw
Copy raw file
Download raw file
Outline
Edit and raw actions

用Array的reduce方法实现map方法(头条一面)

reduce() 方法对数组中的每个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值。

语法 array.reduce(function(total, currentValue, currentIndex, arr){ }, initialValue);

  • total 必需。初始值, 或者计算结束后的返回值。
  • currentValue 必需。当前元素
  • currentIndex 可选。当前元素的索引
  • arr 可选。当前元素所属的数组对象。
  • initialValue可选。传递给函数的初始值
    var arr = [1,2,3];

    var arr2 = arr.reduce((acc,cur) => {
        cur = cur * 2;
        acc.push(cur);
    },[]);

数组扁平化

    var flatten = arr => [].concat(...arr.map(item => Array.isArray(item) ? flatten(item) : item));

    // 方法2
    function flatten(arr) {
        var len = arr.length,
            newArr = [];
        for(var i = 0; i < len; i++) {
            if(arr[i] instanceof Array) {
                newArr = newArr.concat(flatten(arr[i]));
            }else {
                newArr.push(arr[i]);
            }
        }
        return newArr;
    }

手写原生Ajax

    function ajax(url, cb) {
        let xhr;
        if(window.XMLHttpRequest) {
            xhr = new XMLHttpRequest();
        }else {
            xhr = ActiveXObjext('Microsoft.XMLHTTP');
        }
        xhr.open('GET', url, true);
        xhr.onreadystatechange = function() {
            if(xhr.readyState === 4 && xhr.status === 200) {
                cb(xhr.responseText);
            }
        }
        xhr.send();

        // POST请求
        xhr.open("POST", url, true);
        xhr.setRequestHeader("Content-Type": "application/x-www-form-urlencoded");
        xhr.send("key1=value1&key2=value2");
    }

用setTimeout实现setInterval

    const mySetInterval = (cb, time) => {
        const fn = () => {
            cb();
            setTimeout(() => {
                fn();  // 递归调用自己
            }, time);
        }
        setTimeout(fn, time);
    }
You are visitor 01402605 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.