簡體   English   中英

從數組中刪除最后一項(而不是返回項)

[英]Remove the last item from an array (and not return item)

我當前的數組: abc = ['a', 'b', 'c', 'd'];

我理解.pop()刪除並返回數組的最后一項,因此: abc.pop(); = 'd' abc.pop(); = 'd'

但是,我想刪除最后一項,並返回數組。 所以它會返回:

['a', 'b', 'c'];

是否有用於此的 JavaScript 函數?

pop()函數還會從數組中刪除最后一個元素,所以這就是您想要的( JSFiddle 上的演示):

var abc = ['a', 'b', 'c', 'd'];
abc.pop()
alert(abc); // a, b, c

這樣做

abc = abc.splice(0, abc.length-1)

編輯:有人指出,這實際上返回了一個新數組(盡管具有相同的變量名)。

如果要返回相同的數組,則必須創建自己的函數

function popper(arr) {
   arr.pop();
   return arr;
}

在表達式中,使用逗號運算符。
(文檔: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator // thx @Zero )

(abc.length--, abc)    

// expl :
  (abc.length--, abc).sort();

或者在一個函數中,最方便的是將它設置在 Array 原型上:

 Array.prototype.removeLast = function () {
       this.length--;
       return this;
 }

var abc = ['you', 'and', 'me'];
abc.removeLast(); 

你可以菊花鏈:

abc.removeLast().sort();
Array.prototype.popAndReturnArray = function( ){
   this.pop();
   return this;
}

是的,您更普遍地想要的是“過濾器”功能。

它接受一個函數並返回通過測試函數的所有內容,這是一個示例:

abc = ['a', 'b', 'c', 'd'];

abc.filter(function(member,index) { return index !== abc.length - 1; });

Splice 和 pop 都將返回被移除的元素。 它們會改變原始數組,但如果您正在尋找一個函數返回沒有刪除元素的數組,請使用 slice。 這樣你就可以鏈接調用。

 let abc = ['a', 'b', 'c', 'd']; abc = abc.slice(0, -1) .map(value => value += value); console.log(abc); // prints ['aa', 'bb', 'cc']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM