JavaScript学习之—prototype

时间:2021-10-10 07:36:37

一、利用prototype扩展String方法,去除字符前后空格:

String.prototype.trim = function String$trim() {
if (arguments.length !== 0) throw Error.parameterCount();
return this.replace(/^\s+|\s+$/g, '');
}

测试:

var valueStr = "    JAVASCRIPT    ";
alert(valueStr.trim() + "的长度" + valueStr.trim().length);

不管前后有几个空格长度都为10

正则:/^\s+|\s+$/g 匹配以空格开始或结尾的字符串,/g表示会返回多个结果。

二、利用prototype扩展Array方法,实现冒泡排序:

<script type="text/javascript" language="javascript">
Array.prototype.MaxToMin = function() {
var len = this.length;
var arr = new Array(len);
for (var i = 0; i < len; i++) {
for (var j = i + 1; j < len; j++) {
if (this[i] < this[j]) {
var temp = this[i];
this[i] = this[j];
this[j] = temp;
}
}
}
return this;
}

测试:

var ArrayInt = new Array(23, 4, 2, 545, 25, 1, 34, 65, 5, 8, 4, 8, 34, 86, 235, 8, 2345, 8, 3245);
document.write(ArrayInt.MaxToMin());

结果:3245,2345,545,235,86,65,34,34,25,23,8,8,8,8,5,4,4,2,1

对字符串数组的测试:

var arrayString = new Array("bb", "aa", "cc", "dd");
document.write(arrayString.MaxToMin());

结果:dd,cc,bb,aa