<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h4>1111</h4>
<h4>2222</h4>
<h4>3333</h4>
<script type="text/javascript">
var str = "book";
var num = 123;
//function String(){
// console.log("string...")
//}
console.log(str.length, num.length);
console.log("String", String);
var init;
String.prototype.get = function() {
console.log(this);
init = this;
return "好好学习"
}
var str2 = " go od ";
console.log(str2.length);
var strO = new String(" happy NewYear ");
console.log(strO, strO.get(), init === strO); //true
console.log(strO.trim().length);
var str3 = " th a nk ";
if(!String.prototype.trim) {
String.prototype.trim = function() {
return this.replace(/(^\s+|\s+$)/g, ""); //去掉空格
}
}
String.prototype.trimAll = function() {
return this.replace(/\s+/g, ""); //去掉所有空格
}
console.log(str3.trim().length, str3.trim(), str3.trimAll());
console.log("-------------------------------------------------");
console.log(Array.prototype.indexOf);
var objToString = Object.prototype.toString;
var arrSlice = Array.prototype.slice;
var doms = document.getElementsByTagName("h4");
console.log(doms, objToString.call(doms));
function fn1() {
console.log(arguments, objToString.call(arguments));
//console.log(arguments.slice(1)) 出错 arguments不是数组,不具有数组的方法
var a1 = arrSlice.call(arguments, 1);
console.error(a1) //成立
var aa = arrSlice.call(arguments); //将类数组转为数组
console.log(aa);
var arr = [1, 4, 'd'];
console.log(arr.slice());
var a2 = Array.prototype.splice(arguments);
console.log(a2) //[]
console.log([].slice.call(arguments))// 因为[]是数组的实例,所以[]也有slice方法,call方法必须由函数调用,不能直接对象.call
}
fn1(123, "abc");
//https://www.cnblogs.com/guorange/p/6668440.html
//slice的内部实现
Array.prototype.slice = function(start, end) {
var result = new Array();
start = start || 0;
end = end || this.length; //this指向调用的对象,当用了call后,能够改变this的指向,也就是指向传进来的对象,这是关键
for(var i = start; i < end; i++) {
result.push(this[i]);
}
return result;
}
</script>
</body>
</html>
类数组转为数组,重写String去空格的trim方法
最新推荐文章于 2024-04-28 15:15:49 发布