从中删除元素
Remove element from
我试图在不使用任何递归方法的情况下从数组中删除第一个元素。我的代码有什么问题?
为了从数组中删除元素,您通常使用 array.splice(startingPosition, howMuchElementsYou'dLikeToRemove)
,您不能 decrement
数组并从中删除元素,就像您在 post 中所做的那样.
我不确定我是否正确理解了你的问题,但是,这样的事情可能会对你有所帮助:
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);"
如果这与您的问题无关,请更好地编辑您的问题,以便我们了解您的确切需求。希望这有帮助,干杯。
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;
}
我试图在不使用任何递归方法的情况下从数组中删除第一个元素。我的代码有什么问题?
为了从数组中删除元素,您通常使用 array.splice(startingPosition, howMuchElementsYou'dLikeToRemove)
,您不能 decrement
数组并从中删除元素,就像您在 post 中所做的那样.
我不确定我是否正确理解了你的问题,但是,这样的事情可能会对你有所帮助:
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);"
如果这与您的问题无关,请更好地编辑您的问题,以便我们了解您的确切需求。希望这有帮助,干杯。
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;
}