簡體   English   中英

如何擴展javascript中的array.push(),以便在調用push方法之后,元素不應被推入數組中?

[英]how to extend array.push() in javascript such that after calling push method, element should not get pushed into the array?

例:

var animals = ['pigs', 'goats', 'sheep'];

console.log(animals.push('cows'));
// expected output: 4

console.log(animals);
// expected output: Array ["pigs", "goats", "sheep", "cows"]

animals.push('chickens');

//我想要輸出,這樣當我按下“雞”時它不會

pushed into the array.
console.log(animals);
// expected output: Array ["pigs", "goats", "sheep", "cows"]

我的要求是,當我將調用push方法時,它應該顯示“ hii”,但不應該推送任何元素

這不是一個好主意 ,但是您始終可以通過執行以下操作來覆蓋現有的push函數

Array.prototype.push = function(){ console.log("hii") };

演示版

 var arr = [1]; console.log(1,arr); //[1] Array.prototype.push = function(){console.log("hii") }; arr.push(2); //hii console.log(2,arr); //hii //[1] 

注意

  • 您會注意到,在初始化數組並將其值打印在console上時,(內部)調用了push方法。

根據您的情況,問題應該在其他地方出現,因為如果您要修改本機函數,則使用該函數的庫可能會開始返回一些奇怪的值。 但是,如果您確實要執行此操作,建議您使用Array.prototype將.push函數包裝到自己的函數中。 您可以閱讀有關此內容的更多信息https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype

暫無
暫無

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

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