JS 移除数组中的指定元素

165 阅读1分钟

今日练习:使用 JS 删除指定的数组元素,并且返回。
关键方法:splice 、indeOf

先看效果: image.png

直接来吧~


html:
    <h4>splice()方法</h4>
    <p><a href="https://www.runoob.com/html/html-tutorial.html">splice()</a> 方法常用于向数组添加或者删除元素</p>
    <p><strong>注意:</strong>这种方法会改变原数组</p>
    <h5>语法</h5>
    <p>array.splice(index,howmany,item1,.....,itemX)</p>
    <table border="1">
        <thead>
            <tr>
                <th>参数</th>
                <th>描述</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>index</td>
                <td>必需。规定从何处添加/删除元素。<br />
                    该参数是从开始插入(或)删除的数组元素的下标,必须是数字。</td>
            </tr>
            <tr>
                <td>howmany</td>
                <td>可选。规定应该删除多少元素。必须是数字,但可以是 "0"。<br />
                    如果未规定此参数,则删除从 index 开始到原数组结尾的所有元素。</td>
            </tr>
            <tr>
                <td>item1,.....,itemX</td>
                <td>可选。要添加到数组的新元素。</td>
            </tr>
        </tbody>
    </table>
    <br>
    <p>以下代码我们使用 JS 的 splice() 方法来移除数组的指定元素:</p>

随便写点css就好了,可以不写:

        a{
            text-decoration: none;
            color: red;
        }
        thead {
            background-color: #000000;
            color: #ffffff;
        }

        tr:nth-child(2) {
            background-color: #D3D3D3;
        }

js:

    // 创建一个静态数组
    const arr = [1, 2, 5, 7, 9];
    // 在浏览器当前页面中打印出arr数组
    document.write("原素组:"+arr)
    // 移除数组中的2
    const index = arr.indexOf(2)
    // 移除找到指定的元素
    if (index > -1) arr.splice(index, 1);
    document.write('<br />');
    document.write("修改后的数组:"+arr);

本次练习主要用到了两个方法,ok,今天的练习就到这里。
仙路崎岖,磨难并不可怕,坚持终成正果。