Удалить элемент из - PullRequest
       8

Удалить элемент из

0 голосов
/ 30 октября 2018

Я пытаюсь удалить первый элемент из массива без рекурсивных методов. Что не так в моем коде?

Ответы [ 2 ]

0 голосов
/ 30 октября 2018
arr=[1,2,3,4];
function rem(arr){
let res=[];
if(!this.index)  // optional if index is maintaining in outside
    this.index = 0; // optional, this would get created as a global variable & make sure that you haven't use this variable in somewhere else.
if(arr.length>1){
    if (this.index<arr.length-1){
        arr[this.index]=arr[this.index+1];
        this.index++;
        return rem(arr);
    }
    else{
        this.index = undefined; // optional, make it to initial state
        arr.length--;
        return arr;
    }
 }
 this.index = undefined; // optional, make it to initial state
 return res;
 }
0 голосов
/ 30 октября 2018

Чтобы удалить элементы из массива, вы обычно используете array.splice(startingPosition, howMuchElementsYou'dLikeToRemove), вы не можете decrement массив и удалять элементы из него, как вы это делали в своем посте.

Я не уверен, правильно ли я понял ваш вопрос, но что-то вроде этого может вам помочь:

let arr=[4,2];
function rem(arr){
// If the arr length is higher than 2 (which means 3+), delete the first element leaving
// only two elements in the array.
 if(arr.length > 2) {
   // Remove - splice - the FIRST element in the array. (0 - means first element, 1 - is
   // how much elements from that position you'd like to remove from the array).
   arr.splice(0, 1)
 } else {
   // Call the function
   rem(arr);
 }
}
// Call the function
rem(arr);"

Если это не связано с вашим вопросом, пожалуйста, лучше отредактируйте его, чтобы мы поняли, что именно вам нужно. Надеюсь, это поможет, ура.

...