前端面试常考代码-js、css

101 阅读5分钟

常考js代码

1.四种排序算法:冒泡排序、插入排序、快速排序、归并排序及对应的时间复杂度

<!DOCTYPE html>
<html>

<head>
    <title>四种排序算法排序</title>
</head>

<body>
    <script>
        //1.冒泡排序   时间复杂度:O(n^2)
        function bubbleSort(arr) {
            const n = arr.length
            for (let i = 0; i < n - 1; i++) {
                for (let j = 0; j < n - 1 - i; j++) {
                    if (arr[j] > arr[j + 1]) [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]
                }
            }
            return arr
        }
        const arr1 = [2, 3, 6, 9, 1, 4, 5, 3]
        console.log("冒泡排序-----------------------")
        console.log(bubbleSort(arr1))


        // 2.排序实现   时间复杂度:O(n^2)
        function insertSort(arr) {
            for (let i = 1; i < arr.length; i++) {
                const value = arr[i];
                let j = i - 1;
                while (j >= 0) {
                    if (arr[j] > value)
                        arr[j + 1] = arr[j];
                    else
                        break;
                    j--;
                }
                arr[j + 1] = value;
            }
            return arr;
        }

        // 插入排序   
        const a2 = [5, 2, 9, 1, 5, 6];
        console.log("插入排序---------------", insertSort([...a2]));




        // 3.快速排序实现   时间复杂度:O(nlogn)
        function quickSort(arr, left = 0, right = arr.length - 1) {
            if (left >= right) return;

            // 随机选择基准值并交换到左侧
            const pivotIndex = left + Math.floor(Math.random() * (right - left + 1));
            [arr[left], arr[pivotIndex]] = [arr[pivotIndex], arr[left]];

            const pivot = arr[left];
            let l = left;
            let r = right;

            while (l <= r) {
                // 右侧指针寻找小于等于基准值的元素
                while (l <= r && arr[r] >= pivot) r--;

                // 左侧指针寻找大于等于基准值的元素
                while (l <= r && arr[l] <= pivot) l++;
                if (l < r) [arr[l], arr[r]] = [arr[r], arr[l]]

            }

            arr[l] = pivot; // 基准值归位

            quickSort(arr, left, l - 1);   // 递归排序左子数组
            quickSort(arr, l + 1, right);  // 递归排序右子数组

            return arr;
        }

        // 快速排序
        const arr3 = [5, 2, 9, 10, 5, 6, 8];
        quickSort(arr3);
        console.log("快速排序结果---------------------:", arr3);




        //4.归并排序   时间复杂度O(nlogn)
        function mergeSort(arr) {
            if (arr.length <= 1) return arr
            let mid = Math.floor(arr.length / 2)
            let left = arr.slice(0, mid)
            let right = arr.slice(mid)
            return merge(mergeSort(left), mergeSort(right))
        }
        function merge(left, right) {
            const result = []
            let i = 0, j = 0
            while (i < left.length && j < right.length) {
                if (left[i] < right[j]) {
                    result.push(left[i++])
                }
                else {
                    result.push(right[j++])
                }
            }
            return result.concat(left.slice(i).concat(right.slice(j)))
        }
        const arr4 = [10, 90, 50, 60, 80, 30, 20, 60]
        console.log("归并排序--------------------------")
        console.log(mergeSort(arr4))
    </script>
</body>

</html>

2.手写深拷贝的实现(不含循环引用)

<!DOCTYPE html>
<html>
    <head>
        <title>深拷贝</title>
    </head>
    <body>
        <script>
            const obj1={
                name: 'zhangsan',
                age: 18,
                address: {
                    city: 'beijing',
                    street: 'wangfujing'
                },
                hobbies: ['reading', 'gaming']
            }

            // 深拷贝函数
            const deepClone=(obj)=>{
                if(typeof obj!=='object' || typeof obj==null){//基本数据类型直接返回
                    return obj
                }
                let res
                if(obj instanceof Array){
                    res=[]
                }else if (obj instanceof Object){
                    res={}
                }
                for(let key in obj){
                    if(obj.hasOwnProperty(key)){
                        res[key]=deepClone(obj[key])
                    }
                }
                return res
            }
            const obj2=deepClone(obj1)
            const obj3=obj1
            console.log('obj1',obj1)
            console.log('obj2',obj2)
            console.log('obj3',obj3)
            console.log('---------------------------------------------------------------------------------------obj1改变后')
            obj1.age=20
            console.log('obj1', obj1)
            console.log('obj2', obj2)
            console.log('obj3跟着obj1改变而改变')
            console.log('obj3', obj3)

        </script>
    </body>
</html>

3.手写实现promise.all与promise.race

promise.all与promise.race的区别

Promise.allPromise.race 是 JavaScript 中两个常用于并发处理多个异步操作的方法。两者都传入一个数组。

promise.all():

等待所有 Promise 全部成功(fulfilled) ,再返回结果数组;
如果有任意一个失败(rejected) ,立即返回失败。

promise.race():
只要其中一个 Promise 先完成(无论成功还是失败) ,就立即返回那个结果。

<!DOCTYPE html>
<html>

<head>

</head>

<body>
    <script>
        //手写promise.all()
        function myPromiseAll(iterable) {
            return new Promise((resolve, reject) => {
                const promises = Array.from(iterable)

                let result = []
                if (promises.length === 0) {
                    resolve([])
                    return
                }
                
                let count = 0
                for (let i = 0; i < promises.length; i++) {
                    Promise.resolve(promises[i])
                        .then(res => {
                            result[i] = res
                            count++
                            if (count === promises.length) {
                                resolve(result)
                            }
                        }).catch(err => reject(err))
                }
            })

        }


        //手写promise.race()
        function myPromiseRace(iterable) {
            return new Promise((resolve, reject) => {
                const promises = Array.from(iterable);

                if (promises.length === 0) {
                    // 如果没有传入任何 Promise,race 永远不会 resolve 或 reject
                    return;
                }

                for (let i = 0; i < promises.length; i++) {
                    Promise.resolve(promises[i])
                        .then(value => {
                            resolve(value);
                        })
                        .catch(err => reject(err));
                }
            });
        }

    </script>
</body>

</html>

4.手写call、apply、bind

<!DOCTYPE html>
<html>

<head>
    <title>手写call、apply、bind</title>
</head>

<body>
    <script>
        //call
        Function.prototype.MyCall = function (ctx = window, ...args) {
            const fn = Symbol('1')
            ctx[fn] = this
            const result = ctx[fn](...args)
            delete ctx[fn]
            return result
        }
        //apply
        Function.prototype.MyApply = function (ctx = window, args=[]) {
            const fn = Symbol('1')
            ctx[fn] = this
            const result = ctx[fn](...args)
            delete ctx[fn]
            return result
        }
        //bind
        Function.prototype.MyBind = function (ctx = window, ...args1) {
            return (...args2)=>{
                const fn = Symbol('1')
                ctx[fn] = this
                const result = ctx[fn](...args1,...args2)
                delete ctx[fn]
                return result
            }
        }
        
        function show(...args){
            console.log(...args)
            console.log('this.name:',this.name)
        }

        const f=show.MyBind({name:'汪汪叫'},'111','222')
        f()
    </script>
</body>

</html>

5.对 axios 进行二次封装 主要用于统一设置请求基础路径、超时时间、请求头、拦截器(请求与响应)、错误处理等,提高可维护性和复用性。

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>axios的封装</title>
</head>

<body>

    <script src="https://cdn.jsdelivr.net/npm/axios@0.18.0/dist/axios.min.js"></script>
    <script>

        const service = axios.create({
            baseURL: '/api',
            timeout: 5000
        })
        service.interceptors.request.use(
            config => {
                const token = localStorage.getItem('jwt_token')
                if (token) {
                    config.headers['Authorization'] = 'Bearer ' + token;
                }
                return config
            },
            error => Promise.reject(error)
        )
        service.interceptors.response.use(
            response => response.data,
            error => {
                if (error.response) {
                    const { status } = error.response;
                    if (status === 401) {
                        alert('未授权,请重新登录');
                        // 可以跳转登录页
                        // location.href = '/login';
                    } else if (status === 500) {
                        alert('服务器错误,请稍后再试');
                    }
                }
                return Promise.reject(error);
            }
        );


        // 示例:发送 GET 请求
        service.get('/user/info')
            .then(data => {
                console.log('用户信息:', data);
            })
            .catch(err => {
                console.log('请求失败:', err);
            });

    </script>

</body>

</html>

常考css代码

1.水平垂直居中方式(五种)

<!DOCTYPE html>
<html>
    <head>
        <title>
            5种水平垂直居中方式
        </title>
        <style>
            .container1{
                width: 100vw;
                height: 50vh;
                background-color: rgb(26, 105, 155);
                position: relative;

            }
            .d1{
                width: 100px;
                height: 100px;
                background-color: aquamarine;
                position:absolute;
                left: 50%;
                top: 50%;
                transform:translate(-50%,-50%);
            }


            .container2{
                width: 100vw;
                height: 50vh;
                background-color: rgb(15, 141, 52);
                position: relative;
            }
            .d2{
                width: 100px;
                height: 100px;
                background-color: aquamarine;
                position: absolute;
                left: 0;
                right: 0;
                top:0;
                bottom:0;
                margin: auto;
            }

            .container3{
                width: 100vw;
                height: 50vh;
                background-color: rgb(155, 39, 26);
                display: flex;
                justify-content: center;
                align-items: center;
            }
            .d3{
                width: 100px;
                height: 100px;
                background-color: aquamarine;
            }
            .container4{
                width: 100vw;
                height: 50vh;
                background-color: rgb(58, 64, 20);
                display: grid;
                place-items: center;
            }
            .d4{
                width: 100px;
                height: 100px;
                background-color: aquamarine;
            }
            
            .container5{
                width: 100vw;
                height: 50vh;
                background-color: rgb(26, 105, 155);
                display: table-cell;
                text-align: center;
                vertical-align: middle;
            }
            .d5{
                width: 100px;
                height: 100px;
                background-color: aquamarine;
                display: inline-block;
            }
        </style>
    </head>
    <body>
        <div class="container1"><div class="d1">第一种</div></div>
        <div class="container2"><div class="d2">第二种</div></div>
        <div class="container3"><div class="d3">第三种</div></div>
        <div class="container4"><div class="d4">第四种</div></div>
        <div class="container5"><div class="d5">第五种</div></div>
    </body>
</html>

2.两栏布局(一栏固定、一栏自适应)

<!DOCTYPE html>
<html>

<head>
    <style>
        .container {
            display: flex;
            width: 100vw;
            height: 100vh;
        }
        .left {
            flex: 1;;
            background-color: green
        }

        .right {
            flex:1;
            background-color: rgb(29, 58, 176)
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="left"></div>
        <div class="right"></div>
    </div>


</body>

</html>

3.两栏布局(两栏均自适应)

<!DOCTYPE html>
<html>
    <head>
        <title>两栏布局</title>
<style>
  html,body{
    margin: 0;
    padding:0
  }
  .container { position: relative; height: 100vh; }
  .left { 
    position: absolute; 
    left: 0; 
    width: 30%; 
    height: 100%;
    background-color: aqua;
  }
  .right { 
    position: absolute; 
    right: 0; 
    width: 70%; 
    height: 100%;
    background-color: blueviolet;
  }
</style>
<body>
    <div class="container">
        <div class="left">左侧内容</div>
        <div class="right">右侧内容</div>
    </div>
</body>

</html>

4.三角形的实现

<!DOCTYPE html>
<html>
    <head>
        <title>用css画三角形</title>
        <style>
            .container{
                width: 0;
                height: 0;
                border-bottom: 100px solid transparent;
                border-top: 100px solid transparent;
                border-left: 100px dashed transparent;
                border-right: 100px dashed #6b4dcd;/*右边三角形不透明 */
            }
        </style>
    </head>
    <body>
        <div class="container"></div>
    </body>
</html>