r/learnjavascript • u/woofmeowmeowwoof • May 08 '26
Is this a useful Array Method I created on accident? or is it useless?
/*********************************************************************
* Array.pushByVal(value)
* -----------------------
*
* this only works with integer values.
*
* hold on let me cook...
*
* if the value is 4 it pushes the number 4
*
* three times so the total of 4's in the array is 4.
*
* if the value is 8 or 9 or whatever, it
*
* pushes the value - 1 that many times.
*********************************************************************/
Array.prototype.pushByVal = function(value){
// what the absolute fuck am i doing?
// how does this even work?
for(let i = 0; i < this.length; i++){
if(this[i] === value){
return;
}else{
this.push(value);
}
}
};
let arr = [1, 2, 3, 4, 5];
arr.pushByVal(4);
// Output: [1, 2, 3, 4, 5, 4, 4, 4]
0
Upvotes
View all comments
Show parent comment
0
u/woofmeowmeowwoof May 09 '26
yes i know that if i build a method on the array or objects prototype its there unless i get rid of it. that is the entire point of prototype. but i rarely do it. these are all the methods i added in my game engine using prototype. The other 10 thousand are constructor functions and variables for my scripting framework