日期:2014-05-17  浏览次数:20711 次

HTML自定义对象练习
<!--js文件 数组工具对象-->
// JavaScript Document
function arraytool(){}

var ArrayTool = new arraytool();

ArrayTool.getMax = function(arr)
{
	var max = 0;
	for(var i = 1; i < arr.length; i++)
	{
		if(arr[i] >  arr[max])
			max = i;
	}
	return arr[max];
	
}

ArrayTool.getMin = function(arr)
{
	var min = arr[0];
	for(var i = 1; i < arr.length; i++)
	{
		if(arr[i] <  min)
			min = arr[i];
	}
	return min;
	
}

ArrayTool.binarySearch = function(arr, key)
{
	var max, min, mid;
	min = 0;
	max = arr.length - 1;
	while(min <= max)
	{
		mid = (min + max) >> 1;
		if(key > arr[mid])
			min = mid + 1;
		else if(key < arr[mid])
			max = mid - 1;
		else
			return mid;
	}
	return -1;
}

/*
ArrayTool.getMax = getMax;
function getMax(arr)
{
	var max = 0;
	for(var i = 1; i < arr.length; i++)
	{
		if(arr[i] >  arr[max])
			max = i;
	}
	return arr[max];
	
}

ArrayTool.binarySearch = binarySearch;
function binarySearch(arr, key)
{
	var max, min, mid;
	min = 0;
	max = arr.length - 1;
	while(min <= max)
	{
		mid = (min + max) >> 1;
		if(key > arr[mid])
			min = mid + 1;
		else if(key < arr[mid])
			max = mid - 1;
		else
			return mid;
	}
	return -1;
}*/

<!--jsobject.html文件-->

<!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>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
</head>

<body>
<script type="text/javascript" src="arraytool.js"></script>
<script type="text/javascript">
var arr = [1, 3, 5, 6, 9, 12];

var max = ArrayTool.getMax(arr);
var min = ArrayTool.getMin(arr);
var index = ArrayTool.binarySearch(arr, 12);

alert("max = " + max);
alert("min = " + min);
alert("index = " + index);
/*
var arr = [1, 3, 5, 6, 9, 12];
alert("max = " + getMax(arr));

var index = binarySearch(arr, 5);
alert("index = " + index);
*/
</script>

</body>
</html>