js面试题
- unshift 的用法详解
添加元素到数组头部
let arr=[1,2,3,4,5,6]
let res=arr.unshift(0)
console.log(arr)
console.log(res)
Array.prototype.MyUnShift=function(){
const len=arguments.length
for(let i=len-1;i>=0;i--){
this.splice(0,0,arguments[i])
}
return this.length
}
let res2=arr.MyUnShift(-1,-2)
console.log(arr+'\n'+res2)
- 数组去重
Set 判断元素是否相同是用 SameValueZero 算法,只能去重原始类型,引用类型即使值一样引用地址不一样
Array.prototype.myUnique=function(){
return Array.from(new Set (this))
}
用includes方法也只能判别原始类型
Array.prototype.myUnique=function(){
// return Array.from(new Set (this))
let arr=[]
for(let i=0;i<this.length;i++){
if(!arr.includes(this[i])){
arr.push(this[i])
}
}
return arr
}
用filter方法
- 获取指定范围内的随机数
let num
Math.round(num)//四舍五入取整
Math.floor(num)//向下取整
Math.ceil(num)//向上取整
console.log(Math.random(1))//[0,1)的随机数
function fn(min,max){
// [min,max]
// return Math.floor(Math.random(1)*(max-min+1))+min
//(min,max] [0,max-min) [1,max-min+1]
return Math.ceil(Math.random(1)*(max-min))+min+1
}