>  기사  >  웹 프론트엔드  >  JavaScript의 push() 메소드

JavaScript의 push() 메소드

王林
王林원래의
2024-07-18 16:50:11512검색

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>

style.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으로 문의하세요.