[英]how to extend array.push() in javascript such that after calling push method, element should not get pushed into the array?
Example: 例:
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');
//I want output such that, when i will push 'chickens' it should not get //我想要输出,这样当我按下“鸡”时它不会
pushed into the array.
console.log(animals);
// expected output: Array ["pigs", "goats", "sheep", "cows"]
my requirement is like that when i will call push method it should print "hii" but should not push any element
我的要求是,当我将调用push方法时,它应该显示“ hii”,但不应该推送任何元素
Not a good idea , but you can always override the existing push function by doing 这不是一个好主意 ,但是您始终可以通过执行以下操作来覆盖现有的push函数
Array.prototype.push = function(){ console.log("hii") };
Demo 演示版
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]
Note 注意
push
method is being called (internally) when the array is initialized and when its value is printed on console
. console
上时,(内部)调用了push
方法。 From your situation the problem should me somewhere else because if you would modify native function, libraries that use it may start to return some weird values. 根据您的情况,问题应该在其他地方出现,因为如果您要修改本机函数,则使用该函数的库可能会开始返回一些奇怪的值。 but if you really want to do this, I suggest you wrap .push function with your own one using Array.prototype.
但是,如果您确实要执行此操作,建议您使用Array.prototype将.push函数包装到自己的函数中。 You can read more about this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype
您可以阅读有关此内容的更多信息https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.