第一天面试题

53 阅读1分钟

第一天

如何自定义unshift效果

Array.prototype.myUnshift = function(){
  const len = arguments.length

  for(let i = len - 1; i >= 0 ;i--){
    const element = arguments[i]
    this.splice(0,0, element)
  }

  return this.length
}
let arr = [1,5,3,7]
console.log(arr.myUnshift(7,9,4), arr);

数组去重

let arr = [
  {},
  {},
  "",
  "",
  233,
  233,
  123,
  "aio",
  undefined,
  undefined,
  null,
  null,
  NaN,
  NaN,
  [2],
  [2],
  [4, 5, 6],
];
// 第一种
Array.prototype.myUnique = function () {
  return Array.from(new Set(this));
};
console.log(arr.myUnique());

// 第二种
Array.prototype.myUnique = function () {
  let arr = [];

  for(let i = 0; i< this.length; i++){
    if(!arr.includes(this[i])){
      arr.push(this[i])
    }
  }
  return arr;
};
console.log(arr.myUnique());

// 第三种
Array.prototype.myUnique = function () {
  return this.filter((v, idx) => {
    return this.indexOf(v, 0) === idx
  })
};
console.log(arr.myUnique());

如何获取指定范围内的随机数

function fn(min, max){
  // 不包含最大值和最小值
  // return Math.round(Math.random() * (max - min - 2) + min + 1)

  // 包含最大值和最小值
  // return Math.round(Math.random() * (max - min) + min)

  // 不包括最小值   向上取整
  // return Math.ceil(Math.random() * (max - min) + min)

  // 不包括最大值  向下取整
  return Math.floor(Math.random() * (max -min ) + min)
}

fn(1,3)

1-100质数

let count = 0
for(let i = 2; i<= 100 ;i++){
  for(let j = 1; j <=i; j++){
    if(i % j ===0){
      count++
    }
  }
  if(count === 2){
    console.log(i);
  }
  count = 0;
}