Skip to content

Commit c152daf

Browse files
author
huhao
committed
string.indexOf的实现
1 parent 9bc98f7 commit c152daf

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

javascript/indexof.html

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
<!doctype html>
2+
<head>
3+
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
4+
<title>indexOf实现</title>
5+
<script type="text/javascript" charset="utf-8">
6+
String.prototype.indexOf = function(sub){
7+
var pos = 0, len = this.length, sublen = sub.length, i = 0;
8+
while(i < len){
9+
pos = this.charAt(i) == sub.charAt(pos)?pos + 1: pos -1;
10+
if (pos === sublen)
11+
return i - sublen + 1;
12+
i = i + 1;
13+
}
14+
return -1;
15+
};
16+
17+
function test(input, sub)
18+
{
19+
document.writeln('"' + input + '".indexOf("'+ sub + '")='
20+
+ input.indexOf(sub) + '<br>');
21+
}
22+
test('hellhelloworld','hello');
23+
test('hello world','xxoo');
24+
test('hello', 'helloworld');
25+
test('hello world','hello');
26+
</script>
27+
</head>
28+
<body>
29+
30+
</body>
31+
</html>
32+

0 commit comments

Comments
 (0)