繁体   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