判断数组中是否有重复元素

  1. 如果任何值在数组中出现至少两次, 返回返回 ture, 如果数组中每个元素都不相同, 则返回 false
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    let arr = [1,2,3,4,1]
    // 方法一
    function isRepeat(arr) {
    for(var i = 0; i < arr.length; i++) {
    for(var j = i + 1; j < arr.length; j++) {
    if (arr[i] === arr[j]) return true;
    }
    }
    return false
    }
    // 方法二
    function isRepeat(arr) {
    let arg = arr.sort((a, b) => { return a - b });
    for(var i = 0; i < arg.length; i++) {
    if (arg[i] === arg[i + 1]) return true;
    }
    return false;
    }
  2. 找出出现字符最多的字符及次数
  • 输入 ‘abcdaaabcd’
  • 输出 [‘a’, 4]
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    function findStr(str) {
    let obj = {};
    let char = '';
    let count = 0;
    for (let i = 0; i < str.length; i++) {
    let item = str[i];
    if (obj[item] === undefined) {
    obj[item] = 1;
    } else {
    obj[item]++;
    }
    }
    for (let key in obj) {
    if (obj[key] > count) {
    char = key;
    count = obj[key];
    }
    }
    return [char, count];
    }

求数组中连续数最大个数

给定一个数组, 里面的元素全部由0和1组成, 计算其中最大连续1的个数

  • 输入: [1,1,0,1,1,1]
  • 输出: 3
  • 解释: 开头的两位和最后的三位都是连续1, 所以最大连续1的个数是3
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    function isBiggest(arr) {
    let count = null;
    let arg = [];
    for(var i = 0; i < arr.length; i++) {
    if (arr[i] !== arr[i + 1]) {
    count++;
    arg.push(count);
    count = 0;
    continue;
    } else {
    count++;
    }
    }
    return Math.max(...arg)
    }

数组合并&排序

  1. 实现一个函数,将两个数组合并且从小到大排序
  • 输入: [1,2,3], [1,4,8,9]
  • 输出: [1,1,2,3,4,8,9]
    1
    2
    3
    4
    5
    function mergeArr(left = [], right = []) {
    return left.concat(right).sort((a, b) => a - b)
    }

    mergeArr([1,2,3], [1,4,8,9]);
  1. 给 Object 数组进行排序(排序条件是每个元素对象的属性个数)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    // 输入
    var arr1 = [
    {a: 1, b: 2},
    {a: 1, b: 2, c: 3, d: 5},
    {a: 1},
    {a: 1, b: 2, c: 3, d: 4}
    ]
    // 输出
    var arr1 = [
    {a: 1},
    {a: 1, b: 2},
    {a: 1, b: 2, c: 3, d: 5},
    {a: 1, b: 2, c: 3, d: 4}
    ]
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    // 方法一: 双 for
    function sortArr(arr) {
    for (var i = 0; i < arr.length; i++) {
    for (var j = i + 1; j < arr.length; j++) {
    if (Object.keys(arr[i]).length > Object.keys(arr[j]).length) {
    // 常用写法
    let temp = arr[j]
    arr[j] = arr[i]
    arr[i] = temp
    // 精简写法: es6 解构赋值
    [arr[j], arr[i]] = [arr[i], arr[j]]
    }
    }
    }
    return arr
    }
    // 方法二: 记录长度索引, 按长度排序, 按索引找元素
    function sortArr(arr) {
    let temp = [];
    let obj = {};
    for(let i = 0; i < arr.length; i++) {
    // record length
    obj.len = Object.keys(arr[i]).length
    // record index
    obj.index = i
    temp.push(obj);
    obj = {};
    }
    temp.sort((a, b) => {
    return a.len - b.len
    })
    let result = temp.map((item, index) => {
    return arr[item.index]
    })
    return result
    }

反转

  1. 实现一个函数, 将单词顺序反转
  • 输入: “I am a student”
  • 输出: “student a am I”
    1
    2
    3
    4
    5
    6
    7
    // 注意: 因为是反转单词的顺序, 所以需要根据特定的标示来分割和拼接
    function wordsReverse(str) {
    let reverseStr = str.split(' ').reverse().join(' ');
    return reverseStr;
    }

    wordsReverse("I am a student")
  1. 数组反转
  • 输入: [‘I’, ‘ ‘, ‘a’, ‘m’, ‘ ‘, ‘a’, ‘ ‘, ‘s’, ‘t’, ‘u’, ‘d’, ‘e’, ‘n’, ‘t’]
  • 输出: [‘s’, ‘t’, ‘u’, ‘d’, ‘e’, ‘n’, ‘t’, ‘ ‘, ‘a’, ‘ ‘, ‘a, ‘m’, ‘ ‘, ‘I’]
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    function wordsArrayReverse(arr) {
    let reverseArr = [];
    let count = 0;
    for(var i = arr.length; i > -1; i--) {
    if (arr[i - 1] === undefined) {
    if (arr[i] !== ' ') {
    let words = arr.splice(i, 1)
    reverseArr.push(words)
    }
    break;
    }
    if (arr[i] !== ' ') {
    if (arr[i - 1] !== ' ') {
    count++;
    continue;
    } else {
    let words = arr.splice(i, count)
    reverseArr.push(words)
    }
    } else {
    arr.splice(i, 1)
    reverseArr.push(' ')
    }
    }
    return reverseArr;
    }

    let arr = ['I', ' ', 'a', 'm', ' ', 'a', ' ', 's', 't', 'u', 'd', 'e', 'n', 't']
    wordsArrayReverse(arr)

获取 url 中的参数

  • 输入 ‘https://www.baidu.com?name=%E5%BC%A0%E4%B8%89&age=21'
  • 输出 {name: ‘张三’, age: ‘21’}
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    function getURL(website) {
    // whatever input or get website url except "?"
    let url = website
    ? website.match(/\?{1}.+/)[0].slice(1)
    : location.search.slice(1);
    let splitURL = null;
    let obj = {};
    // if url doesn't exist, return false
    if (!url) throw new TypeError('This is not defined!')
    // if url has more contents, split it
    if (url.includes('&')) {
    splitContent = url.split("&");
    for (let i = 0; i < splitContent.length; i++) {
    splitURL = splitContent[i].split("=");
    obj[splitURL[0]] = splitURL[1];
    }
    }
    // if url only has one content
    else {
    splitURL = url.split("=");
    obj[splitURL[0]] = splitURL[1];
    }
    return obj;
    }

Promise 化

实现如下函数
delay(1000).then(res => console.log(1000)) 可以延迟一秒打印1000

1
2
3
4
5
6
function delay(timer) {
then = (res) => {
res();
}
return new Promise(resolve => setTimeout(resolve, timer))
}

函数柯里化

  • 实现 add(1)(2)(3)(4), 输出结果返回 10
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    function add(a) {
    return function (b) {
    return function (c) {
    return function (d) {
    return a + b + c + d;
    }
    }
    }
    }

    // 函数柯里化 //
    // 定长参数
    function add(a, b, c, d) {
    return [ ...arguments ].reduce((a, b) => a + b)
    }
    function currying(fn) {
    let len = fn.length;
    let args = [];
    return function _c(...newArgs) {
    // 合并参数
    args = [
    ...args,
    ...newArgs
    ]
    // 判断当前参数集合 args 的长度是否小于目标函数 fn 的需求参数长度
    if (args.length < len) {
    // 继续返回函数
    return _c;
    } else {
    // 返回执行结果
    return fn.apply(this, args.slice(0, len));
    }
    }
    }
    let addCurry = currying(add);
    let total = addCurry(1)(2)(3)(4); // 同时支持 addCurry(1)(2, 3)(4) 方式调用
    console.log(total); // 10

    // 不定长参数
    function add(...args) {
    return args.reduce((a, b) => a + b);
    }
    function currying(fn) {
    let args = [];
    return function _c(...newArgs) {
    if (newArgs.length) {
    args = [
    ...args,
    ...newArgs
    ]
    return _c
    } else {
    return fn.apply(this, args);
    }
    }
    }
    let addCurry = currying(add);
    let total = addCurry(1)(2)(3)(4, 5)();
    console.log(total)

a == 1 && a == 2 && a == 3

stackoverflow

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// 在什么情况下, 下面的代码会输出 1
var a = ?
if (a == 1 && a == 2 && a == 3) { console.log(1) }

// 利用 valueOf
var a = {
n: 0,
valueOf() {
return ++this.n;
}
}

// 思路2
var aᅠ = 1;
var a = 2;
var ᅠa = 3;
// 等价于
var a_ = 1;
var a = 2;
var _a = 3;

// 思路3
a = [1,2,3];
a.join = a.shift;

// 思路4
let i = 0;
let a = { [Symbol.toPrimitive]: () => ++i };

实现 Array.prototype.map

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
Array.prototype.myMap = function (callback/*, thisArg*/) {
var T, A, K;
if (this == null) {
throw new TypeError('this is null or not defined');
}
// 1. Let O be the result of calling ToObject passing the |this|
// value as the argument
var O = Object(this);
// 2. Let lenValue be the result of calling the Get internal
// method of O with the argument 'length'
// 3. Let len be ToUnit32(lenValue)
var len = O.length >>> 0;
// 4. If IsCallable(callback) is false, throw a TypeError exception.
// See: http://es5.github.com/#x9.11
if (typeof callback !== 'function') {
throw new TypeError(callback + ' is not a function');
}
// 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
if (arguments.length > 1) {
T = arguments[1];
}
// 6. Let A be a new array created as if by the expression new Array(len)
// where Array is the standard built-in constructor with that name and
// len is the value of len.
A = new Array(len);
// 7. let k be 0
k = 0;
// 8. Repeat, while k < len
while (k < len) {
var kValue, mappedValue;
// a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the HasProperty internal
// method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
if (k in O) {
// i. Let kValue be the result of calling the Get internal
// method of O with argument Pk.
kValue = O[k];
// ii. Let mappedValue be the result of calling the Call internal
// method of callback with T as the this calue and argument
// list containing kValue, k, and O
mappedValue = callback.call(T, kValue, k, O);
// iii. Call the DefineOwnProperty internal method of A with arguments
// Pk, Property Descriptor
// { Value: mappedValue,
// Writable: true,
// Enumerable: true,
// Configurable: true },
// and false.

// In browsers that support Object.defineProperty, use the following:
// Object.defineProperty(A, k, {
// value: mappedValue,
// writable: true,
// enumerable: true,
// configurable: true
// });

// For best browser support, use the following:
A[k] = mappedValue;
}
// d. Increase k by 1.
k++;
}
// 9. return A
return A;
}