js笔试题集合

1、用递归算法实现,数组长度为5且元素的随机数在2-32间不重复的值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
    function getRandomNum(arr) {
        let val = Math.floor(Math.random()*31 + 2);
        if (arr.includes(val)) {
            return getRandomNum(arr);
        } else {
            return val;
        }
    }
    function createArr(arr) {
        if (arr.length === 5) {
            return arr;
        }
        let val = getRandomNum(arr);
        arr.push(val);
        createArr(arr);
    }
    createArr([]);
1
2
3
4
5
6
7
8
9
    function createSet(set) {
        if (set.size >= 5) {
            return set;
        }
        let val = Math.floor(Math.random()*31 + 2);
        set.add(val);
        createSet(set);
    }
    createSet(new Set());

第二种方法是利用Set数据的唯一性,也可以用Set做数组去重。

2、写一个方法去掉字符串中的空格

1
2
3
4
5
function removeSpace(str) {
    let val = str.replace(/\s/g, '');
    return val;
}
removeSpace('  s t  r  ');
1
2
let str = '  s t  r  ';
console.log(str.split(' ').join(''));
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
const str = '  s t  r  '

const POSITION = Object.freeze({
  left: Symbol(),
  right: Symbol(),
  both: Symbol(),
  center: Symbol(),
  all: Symbol(),
})

function trim(str, position = POSITION.both) {
  if (!!POSITION[position]) throw new Error('unexpected position value')
  
  switch(position) {
      case(POSITION.left):
        str = str.replace(/^\s+/, '')
        break;
      case(POSITION.right):
        str = str.replace(/\s+$/, '')
        break;
      case(POSITION.both):
        str = str.replace(/^\s+/, '').replace(/\s+$/, '')
        break;
      case(POSITION.center):
        while (str.match(/\w\s+\w/)) {
          str = str.replace(/(\w)(\s+)(\w)/, `$1$3`)
        }
        break;
      case(POSITION.all):
        str = str.replace(/\s/g, '')
        break;
      default: 
  }
  
  return str
}

const result = trim(str)

console.log(`|${result}|`) //  |s t  r| 

第三种写法是比较完整的。

3、去除字符串中最后一个指定的字符

1
2
3
4
5
6
7
8
9
10
11
String.prototype.reverse = function () {
    return this.split('').reverse().join('')
}

String.prototype.removeFirstChar = function (m) {
    return this.replace(m, '')
}

const string = 'emamam, your string'
const removedChar = 'm'
string.reverse().removeFirstChar(removedChar).reverse()

4、