[英]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.