之前看书的时候看到书上说slice()返回不包括结束位置的字符串,而substring()和slice()的唯一不同是返回了包含了结束位置的字符串

但是实际用的时候发现,这不是都不包括么,忽悠我呢?!……自己试:

代码
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
<title>Untitled Document</title>
</head>
<body>
<div id="div1">1 </div>
<div id="div2">2 </div>
<div id="div3">3 </div>
<div id="div4">4 </div>
<div id="div5">5 </div>
<div id="div6">6 </div>
<div id="div7">7 </div>
<div id="div8">8 </div>
<hr/>
<div id="div11">1 </div>
<div id="div12">2 </div>
<div id="div13">3 </div>
<div id="div14">4 </div>
<div id="div15">5 </div>
<div id="div16">6 </div>
<div id="div17">7 </div>
<div id="div18">8 </div>
<hr/>
<div id="div21">1 </div>
<div id="div22">2 </div>
<div id="div23">3 </div>
<div id="div24">4 </div>
<div id="div25">5 </div>
<div id="div26">6 </div>
<div id="div27">7 </div>
<div id="div28">8 </div>
</body>
<script type="text/javascript">
var s = "liminality";

document.getElementById(
"div1").innerHTML+=s.slice(0,9);
document.getElementById(
"div2").innerHTML+=s.slice(0,-1);
document.getElementById(
"div3").innerHTML+=s.slice(3,4);
document.getElementById(
"div4").innerHTML+=s.slice(3);
document.getElementById(
"div5").innerHTML+=s.slice(-3);
document.getElementById(
"div6").innerHTML+=s.slice(3,-3);
document.getElementById(
"div7").innerHTML+=s.slice(-3,3);
document.getElementById(
"div8").innerHTML+=s.slice();

document.getElementById(
"div11").innerHTML+=s.substring(0,9);
document.getElementById(
"div12").innerHTML+=s.substring(0,-1);
document.getElementById(
"div13").innerHTML+=s.substring(3,4);
document.getElementById(
"div14").innerHTML+=s.substring(3);
document.getElementById(
"div15").innerHTML+=s.substring(-3);
document.getElementById(
"div16").innerHTML+=s.substring(3,-3);
document.getElementById(
"div17").innerHTML+=s.substring(-3,3);
document.getElementById(
"div18").innerHTML+=s.substring();

document.getElementById(
"div21").innerHTML+=s.substr(0,9);
document.getElementById(
"div22").innerHTML+=s.substr(0,-1);
document.getElementById(
"div23").innerHTML+=s.substr(3,4);
document.getElementById(
"div24").innerHTML+=s.substr(3);
document.getElementById(
"div25").innerHTML+=s.substr(-3);
document.getElementById(
"div26").innerHTML+=s.substr(3,-3);
document.getElementById(
"div27").innerHTML+=s.substr(-3,3);
document.getElementById(
"div28").innerHTML+=s.substr();
</script>
</html>

 

结果:
1 liminalit
2 liminalit
3 i
4 inality
5 ity
6 inal
7
8 liminality

1 liminalit
2
3 i
4 inality
5 liminality
6 lim
7 lim
8 liminality

1 liminalit
2
3 inal
4 inality
5 ity
6
7 ity
8 liminality

貌似slice()跟substring()用法差不多,都是从一个开始位置到一个结束位置,只填一个参数那就是个开始位置,结束位置默认为字符串的length;都不填就默认为从0到length。不过slice()可以用负数,-1就是指倒数第一个字符,而substring()不能,貌似负数都会被认为是0。substring()如果开始位置的参数比结束位置的参数大,就会把2者反一下再输出,而slice()则不会(在slice()里,不能说是开始比结束参数大,而是要说开始比结束的字符串位置靠后,因为slice()里能用负数的哈哈)。
substr()就是一个开始位置和一个指定的长度,前者可为负数,这点跟slice()一样,后者是长度么肯定不能用负数了呵呵……
posted on 2010-03-21 23:04  水忧狐  阅读(812)  评论(0编辑  收藏  举报