program story

배열의 첫 번째 항목 제거 (예 : 스택에서 팝핑)

inputbox 2020. 10. 28. 08:03
반응형

배열의 첫 번째 항목 제거 (예 : 스택에서 팝핑)


이 질문에 이미 답변이 있습니다.

를 통해 만든 항목 목록이 있습니다 ng-repeat. 또한 삭제 버튼이 있습니다. 삭제 버튼을 클릭하면 배열의 마지막 항목이 하나씩 제거됩니다. 플 런커

하지만 첫 번째 항목부터 하나씩 항목을 제거하고 싶습니다. 어떻게 할 수 있습니까? 목록 항목을 제거하기 위해 이것을 사용했습니다.

  $scope.index = 1;
  $scope.remove = function(item) { 
    var index = $scope.cards.indexOf(item);
    $scope.cards.splice(index, 1);     
  }

상단에서 제거 할 수있는 방법이 있습니까?


가장 쉬운 방법은 shift(). 배열이있는 경우 shift함수는 모든 것을 왼쪽으로 이동합니다.

var arr = [1, 2, 3, 4]; 
var theRemovedElement = arr.shift(); // theRemovedElement == 1
console.log(arr); // [2, 3, 4]

사용하십시오 arr.slice(startingIndex, endingIndex).

를 지정하지 않으면 endingIndex제공된 색인에서 시작하는 모든 항목이 반환됩니다.

귀하의 경우 arr=arr.slice(1).


const a = [1, 2, 3]; // -> [2, 3]

// Mutable solutions: update array 'a', 'c' will contain the removed item
const c = a.shift(); // prefered mutable way
const [c] = a.splice(0, 1);

// Immutable solutions: create new array 'b' and leave array 'a' untouched
const b = a.slice(1); // prefered immutable way
const b = a.filter((_, i) => i > 0);
const [c, ...b] = a; // c: the removed item

플 런커

$scope.remove = function(item) { 
    $scope.cards.splice(0, 1);     
  }

..을 (를) 변경했습니다. 이제 상단에서 제거됩니다.


라는 함수가 shift()있습니다. 배열의 첫 번째 요소를 제거합니다.

좋은 문서와 예제가 있습니다.

참고 URL : https://stackoverflow.com/questions/29605929/remove-first-item-of-the-array-like-popping-from-stack

반응형