JavaScript中prototype(原型)給字串物件新增一個toCharArray的方法,reverse(翻轉)的 方法
阿新 • • 發佈:2018-11-15
<!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=utf-8" />
<title>無標題文件</title>
var arr = new Array();
for(var index = 0; index<this.length; index++){
arr[index]=this.charAt(index);
}
return arr;
var arr = this.toCharArray();
arr.reverse();
return arr.join(" ");
}
var str = "厲害了";
var chaArr = str.toCharArray();
document.write("陣列的元素:"+chaArr.join(","));
str = str.reverse();
document.write("翻轉後的字串:"+str);
</script>
</head>
<body>
</body>
</html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>無標題文件</title>
/*
需求:利用prototype(原型)給字串物件新增一個toCharArray的方法,然後再新增一個reverse(翻轉)的 方法
*/
<script type="text/javascript">
//字串物件新增一個toCharArray的方法
var arr = new Array();
for(var index = 0; index<this.length; index++){
arr[index]=this.charAt(index);
}
return arr;
}
//字串物件新增reverse(翻轉)的 方法
String.prototype.reverse = function(){arr.reverse();
return arr.join(" ");
}
var str = "厲害了";
var chaArr = str.toCharArray();
document.write("陣列的元素:"+chaArr.join(","));
str = str.reverse();
document.write("翻轉後的字串:"+str);
</script>
</head>
<body>
</body>
</html>