简体   繁体   中英

How can I define a new prototype methods to arrays for count based the number passed to the method parameter?

I want to create the method for array prototype that counts in the array the value passed to the parameter of this method:

 Object.defineProperties(Array.prototype, { countValues: function(numb) { return this.filter((value, index) => value === numb).length } }) const newArr = [1, 2, 3, 4, 4] newArr.countValues(4) //Would return 2

Why doesn't the code work?

The values passed to Object.defineProperties should be property descriptors , not just the plain values you want the prototype to be. In the property descriptor, you can define the value (as well as other descriptor options like if you want the property to be enumerable or writable):

 Object.defineProperties(Array.prototype, { countValues: { value: function(numb) { return this.filter((value, index) => value === numb).length } } }) const newArr = [1, 2, 3, 4, 4] console.log(newArr.countValues(4)) //Would return 2

In your original code, the value you give for countValues isn't a property descriptor, so it doesn't appear to do anything. (what it does is assign a non-configurable, non-writable property to Array.prototype whose value is undefined )

You can make the code slightly more efficient by using reduce instead of .filter and .length , thereby avoiding the creation of an intermediate array:

 Object.defineProperties(Array.prototype, { countValues: { value: function(numb) { return this.reduce((a, b) => a + (b === numb), 0); } } }) const newArr = [1, 2, 3, 4, 4] console.log(newArr.countValues(4)) //Would return 2

Since you're only defining one property, you could also consider using Object.defineProperty :

 Object.defineProperty(Array.prototype, 'countValues', { value(num) { return this.reduce((a, b) => a + (b === num), 0); } }); const newArr = [1, 2, 3, 4, 4] console.log(newArr.countValues(4)) //Would return 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM