首页  >  文章  >  web前端  >  JavaScript 中的 push() 方法

JavaScript 中的 push() 方法

王林
王林原创
2024-07-18 16:50:11510浏览

JavaScript 中的 push() 方法将一个或多个元素添加到数组的末尾。该方法修改原始数组并返回数组的新长度。

语法:

array.push(element1, element2, ..., elementN);

*示例 1.:*

const fruits = ["Apple", "Banana"];
fruits.push("Orange", "Mango");
console.log(fruits); // Output: ["Apple", "Banana", "Orange", "Mango"]

*示例 2.: *
如何使用push()方法动态添加元素

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Fruit List</title>
   <link rel="stylesheet" href="style.css">
</head>
<body>
    <div id="container">
        <h2>Fruit List</h2>
        <input type="text" id="addEle" placeholder="Enter fruit name..." />
        <button onclick="AddEle()">Add Element</button>
        <h4 id="ans"></h4>
    </div>
    <script>
        function AddEle() {
            const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango", "Strawberry"];
            const NewVal = document.getElementById("addEle").value;

            if (NewVal === "") {
                alert("Please Enter Fruit Name..!");
            } else {
                fruits.push(NewVal); 
                document.getElementById("ans").innerHTML = fruits.join(", ");
                document.getElementById("addEle").value = ""; 
            }
        }
    </script>
</body>
</html>

样式.css

 body {
            font-family: Arial, sans-serif;
            margin: 20px;
            padding: 0;
        }
        #container {
            max-width: 500px;
            margin: 0 auto;
            padding: 20px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        h2 {
            text-align: center;
        }
        input[type="text"] {
            width: calc(100% - 24px);
            padding: 10px;
            margin-bottom: 10px;
            border: 1px solid #ccc;
            border-radius: 3px;
        }
        button {
            width: 100%;
            padding: 10px;
            background-color: #28a745;
            color: #fff;
            border: none;
            border-radius: 3px;
            cursor: pointer;
        }
        button:hover {
            background-color: #218838;
        }
        h4 {
            margin-top: 20px;
            color: #555;
        }

Image description

以上是JavaScript 中的 push() 方法的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn