前端面试题_1

136 阅读2分钟

判断对象和数组

以下这种方式是不可取的。

const obj = {}
const arr = [] 
console.log(typeof obj) // object 
console.log(typeof arr) // object 

使用以下方式倒是可以,但也有缺点。

const arr = []
// 原理 prototype 属性是否在 左边的原型链上(同时也是缺点,当原型链被修改则无法判断)
console.log(arr instanceof Array)  // true
console.log(Object.getPrototypeOf(arr) === Array.prototype)// true
console.log(Array.prototype.isPrototypeOf(arr))// true
arr.__proto__ = function () {}
console.log(arr instanceof Array)  // false 其他的都同理 false

还有constructor,也是类似的缺点,自身被修改就无法判断。

arr.constructor = function () {}
console.log(arr.constructor === Array)

这时可以使用如下方法:

const arr = []
// 调用原型链顶端的 toString
console.log(Object.prototype.toString.call(arr) === '[object Array]') // true
console.log(Array.isArray(arr)) // true 但可能存在兼容性问题

找出某个网站中不重复的 html 标签

/**
 * 1. 找出所有的html标签
 * 2. 去重
 */
// ES6
[...new Set([...document.querySelectorAll("*")].map(v => v.tagName))];
// ES5
[...new Set(Array.prototype.slice.call(document.querySelectorAll("*")).map(v => v.tagName))]

找出某个字符串中出现次数最多的字符

const str = 'aaaabbbbccccc'

function transformStr(str) {
    let strObj = {}
    for (let i = 0; i < str.length; i++) {
        let char = str.charAt(i)
        if (strObj[char]) {
            strObj[char]++
        } else {
            strObj[char] = 1
        }
    }
    let maxChar = null
    let max = 0
    for (let strObjKey in strObj) {
        if (strObj[strObjKey] > max) {
            max = strObj[strObjKey]
            maxChar = strObjKey
        }
    }
    console.log(`出现最多的字符为:${maxChar}, 出现的最多次数为:${max}`)
}
transformStr(str)

动态打印当前时间

/**
 * 动态打印当前时间 YYYY-MM-DD hh:mm:ss
 */
function timer() {
    let date = new Date()
    let year = date.getFullYear()
    let month = (date.getMonth() + 1).toString().padStart(2, '0')
    let day = date.getDay().toString().padStart(2, '0')
    let hour = date.getHours().toString().padStart(2, '0')
    let minutes = date.getMinutes().toString().padStart(2, '0')
    let second = date.getSeconds().toString().padStart(2, '0')
    return `现在的时间是:${year}-${month}-${day} ${hour}-${minutes}-${second}`
}

setInterval(() => {
    console.log(timer())
}, 1000)

计算参数和

function getSum() {
    let sum = 0
    for (let i = 0; i < arguments.length; i++) {
        if (!isNaN(arguments[i])) {
            sum += Number(arguments[i])
        }
    }
    return sum
}

console.log(getSum(1,2,'3'))

代码优化(提前返回)

function printAnimalDetails(animal) {
    let result = null
    if (animal) {
        if (animal.type) {
            if (animal.name) {
                if (animal.gender) {
                    result += `${animal.name} is a ${animal.gender} ${animal.type}`
                } else {
                    result = 'no animal gender'
                }
            } else {
                result = 'no animal name'
            }
        } else {
            result = 'no animal type'
        }
    } else {
        result = 'no animal'
    }
    return result
}
// 优化为:
function printAnimalDetailsPlus({type, name, gender} = {}) {
    if (!type && !name && !gender) return 'no animal'
    if (!type) return 'no animal type'
    if (!name) return 'no animal name'
    if (!gender) return 'no animal gender'
    return `${name} is ${gender} ${type}`
}

获取随机数

function randomNum(min, max) {
    return min + Math.round((max - min) * Math.random())
}

Math.random()  静态方法返回一个大于等于 0 且小于 1 的伪随机浮点数。

this 指向

let name = 222
let a = {
    name: 111,
    say: function () {
        console.log(this.name)
    }
}
// 将 say 函数的作用域给到 window
let fun = a.say
fun() // 222
a.say() // 111

let b = {
    name: 333,
    say: function (fun) { //fun = a.say
        fun()
    },
}
b.say(a.say) // 222
b.say = a.say
b.say() //333

// function get(callback) {
//     callback()
// }
//
// function fn() {
//     console.log(this)
// }
//
// get(fn) // window

手写 map

/**
 * map:映射、设置this指向、返回新的数组
 */
Array.prototype.myMap = function (fn) {
    let res = []
    let thisArg = arguments[1] || window
    if (typeof fn === 'function') {
        for (let i = 0; i < this.length; i++) {
            res.push(fn.call(thisArg, this[i], i, this))
        }
    } else {
        throw new Error('fn is not a function')
    }
    return res
};
let arr = [1, 2, 3, 4]
let res = arr.myMap(function (item, index, arr) {
    return item + 1
});
console.log(res)