js basic review 7-prototype object usage-use prototype objects to extend built-in object methods

Let's first look at what is on the prototype object of the array:

console.log(Array.prototype)

Insert picture description here
These are the methods provided by arrays, but there is no sum method. We can use the prototype object to extend the built-in object methods, such as adding an array sum method:

<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>
<body>
	<script type="text/javascript">
		console.log(Array.prototype)
		Array.prototype.sum = function() {
    
    
			var result = 0
			for (var i=0; i<this.length; i++) {
    
    
				result += this[i]
			}
			return result
		}
		var arrSum = [1,2,3,4,5].sum()
		console.log(arrSum)
	</script>
</body>
</html>

Insert picture description here
Now the array also has a sum function

Guess you like

Origin blog.csdn.net/dyw3390199/article/details/114964205