js 實現僞數組轉成真數組Array.prototype.slice.call(僞數組).forEach(()=>{})

實現僞數組轉成真數組

實現方法:Array.prototype.slice.call(僞數組).forEach(()=>{})

示例:


<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js">script>
    <title>Documenttitle>
    <style>
        ul>li{
            list-style: none;
            background-color: pink;
            margin:10px 0;
        }
    style>
head>

<body>
    <div id="app">
        <ul ref="ulParent">
            <li style="height: 20px;">li-1li>
            <li style="height: 50px;">li-2li>
            <li style="height: 30px;">li-3li>
            <li style="height: 70px;">li-4li>
            <li style="height: 40px;">li-5li>
        ul>
        <button @click="getLiHeight">獲取所以li高度button>
        <div>
            <p>所有li高度p>
            {{liHeight}}
        div>
    div>
    <script>
        const app = new Vue({
            el: '#app',
            data: {
                liHeight:[]
            },
            methods:{
                getLiHeight(){
                    // lis 為僞數組
                    let lis = this.$refs.ulParent.getElementsByTagName('li');
                    // 轉成 真數組 
                    let liArr = Array.prototype.slice.call(lis);
                    // 獲取li高度
                    let liHeight = [];
                    liArr.forEach(li => {
                        liHeight.push(li.clientHeight);
                    });
                    this.liHeight = liHeight;
                }
            }
        })
    script>
body>

html>

示例結果

js 實現僞數組轉成真數組Array.prototype.slice.call(僞數組).forEach(()=>{})_第1张图片

你可能感兴趣的:(前端小案例)