웹 프로그래밍 기초/객체

splice(), slice()

별초롱언니 2025. 4. 7. 21:48

splice() 메서드는 주어진 값의 위치부터 시작하여 정의된 수만큼 배열 요소를 삭제하거나 다음에 주어진 배열 요소를 추가한다. 즉, 배열의 일부를 교체하는 역할이다.

 

array.splice(star_index, delete_count, item1, item2, ... , itemn);

array.slice(star_index, end_index);

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    let fruits = ["apple","pear","orange"];
    fruits.splice(2,1, "lemon","mango"); // 인덱스 2부터 1개의 요소 값을 제거하고 그 자리에 2개의 요소 추가한다.
    document.write(fruits);
  </script>
</body>
</html>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    let fruits = ["apple","pear","orange","pear","kiwi"];
    let remove_fruits = fruits.splice(2,2);  // 인덱스 2부터 1개의 요소 값을 제거하고 그 자리에 2개의 요소 추가한다. 

    document.write(fruits);
  </script>
</body>
</html>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    let fruits = ["apple","pear","orange","pear","kiwi"];
    
    let eat_fruits = fruits.slice(1,3); // 인덱스 1부터 3이전까지 배열 요소 추출
    document.write("원래 배열 : " + fruits + "<br>");
    document.write("추출된 배열 요소 : " + eat_fruits + "<br>");

    let eat_fruits2 = fruits.slice(3);
    document.write("원래 배열 : " + fruits + "<br>");
    document.write("추출된 배열 요소 : " + eat_fruits2 + "<br>");
  </script>
</body>
</html>

'웹 프로그래밍 기초 > 객체' 카테고리의 다른 글

delete 연산자  (0) 2025.04.07
sort(), reverse()  (0) 2025.04.07
shift(), unshift()  (0) 2025.04.07
indexOf()  (0) 2025.04.07
push(), pop()  (0) 2025.04.07