배열에서 첫 번째와 마지막 요소를 제거하는 방법은 무엇입니까?
예를 들면 :
var fruits = ["Banana", "Orange", "Apple", "Mango"];
예상 출력 배열 :
["Orange", "Apple"]
답변
fruits.shift(); // Removes the first element from an array and returns only that element.
fruits.pop(); // Removes the last element from an array and returns only that element.
답변
1 레벨 전체 복사본을 만듭니다.
fruits.slice(1, -1)
원래 배열을 놓으십시오.
철자 오류를 지적 해 주신 @Tim에게 감사드립니다.
답변
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var newFruits = fruits.slice(1, -1);
console.log(newFruits); // ["Orange", "Apple"];
여기서 -1은 배열의 마지막 요소를 나타내고 1은 두 번째 요소를 나타냅니다.
답변
스플 라이스 방식을 사용합니다.
fruits.splice(0, 1); // Removes first array element
var lastElementIndex = fruits.length-1; // Gets last element index
fruits.splice(lastElementIndex, 1); // Removes last array element
마지막 요소를 제거하려면 다음과 같이 할 수도 있습니다.
fruits.splice(-1, 1);
참조 배열에서 마지막 항목을 제거 그것에 대한 자세한 설명을 볼 수 있습니다.
답변
push()
배열 끝에 새 요소를 추가합니다.
pop()
배열의 끝에서 요소를 제거합니다.
unshift()
배열의 시작 부분에 새 요소를 추가합니다.
shift()
배열의 시작 부분에서 요소를 제거합니다.
배열에서 첫 번째 요소를 제거하려면 배열 arr
에서 arr.shift()
마지막 요소를 제거하려면 다음을 arr
사용하십시오.arr.pop()
답변
Array.prototype.reduce ()를 사용할 수 있습니다. .
암호:
const fruits = ['Banana', 'Orange', 'Apple', 'Mango'],
result = fruits.reduce((a, c, i, array) => 0 === i || array.length - 1 === i ? a : [...a, c], []);
console.log(result);
답변
배열에서 요소를 제거하려면 다음을 수행하십시오.
let array_splited = [].split('/');
array_splited.pop()
array_splited.join('/')