我试图从数组中删除第一个元素,而无需递归使用任何方法。我的代码有什么问题?
答案 0 :(得分:0)
要从数组中删除元素,通常使用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);"
如果这与您的问题无关,请更好地编辑您的问题,以便我们了解您的确切需求。希望这会有所帮助,加油。
答案 1 :(得分:0)
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;
}