小说网站 搜小说 无限网 烟雨红尘 小说爱好者 免费小说 免费小说网站

javascript之自定义数组工具对象

<pre name="code" class="html">/*
需求:编写一个js文件,在js文件中自定义一个数组工具对象,
该工具对象要有一个找到最大值的方法,与找元素对应的索引值的方法。	
*/

这个代码在ArrayTool.js文件中
//创建ArrayTool的对象
 
var tool = new ArrayTool();

function ArrayTool(){
	
	//找最大值
	this.getMax = function(arr){
		var max = arr[0];
		for(var i = 1 ; i<arr.length ;i++){
			if(arr[i]>max){
				max = arr[i];	
			}	
		}
		return max;
	}
	
	//找元素 的索引值
	this.searchEle = function(arr,target){
		for(var i = 0 ; i<arr.length  ; i++){
			if(arr[i] ==target){
				return i;	
			}	
		}	
		return -1;
	}

}


在html里引入.js的代码

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="ArrayTool.js" type="text/javascript"></script>
<script type="text/javascript"> 
 
	var arr = [12,15,9,4];
	var max = tool.getMax(arr);
	document.write("最大值:"+ max+"<br/>");
	
	var index = tool.searchEle(arr,9);
	document.write("找到的索引值是:"+ index);
 
 
 
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>
 
<body>
</body>
</html>





posted on 2016-05-23 22:35  王小航  阅读(285)  评论(0编辑  收藏  举报

导航