Home >Web Front-end >JS Tutorial >Example tutorial based on array extension function in JS

Example tutorial based on array extension function in JS

零下一度
零下一度Original
2017-06-15 13:35:521202browse

This article mainly introduces the JS method of finding the sum of the starting item to the ending item of an array. This function is implemented based on the array extension function, and involves JavaScript's simple judgment, traversal and other related operation skills for arrays. Friends who need it can Refer to the following

The example of this article describes the JS method of finding the sum of the starting item to the ending item of an array. Share it with everyone for your reference, the details are as follows:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS求数组之和</title>
</head>
<body>
<script >
Array.prototype.sum= function(l,r){
l=l==undefined ? 0 : l;
r=r==undefined ? this.length - 1 : r;
var s = 0;
for(var i = l;i <= r;i++){s+=this[i];}
return s;
}
var ar = new Array(1,3,4,-1,-2,3,4,-2,4);
console.log(ar.sum(0,2))
</script>
</body>
</html>

The operation effect diagram is as follows:

The above is the detailed content of Example tutorial based on array extension function in JS. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn