<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="../css/mystyle.css" type="text/css">
<script>
fr = ["사과", "바나나", "참외","사과","복숭아","사과","파인애플"];
function proc1(){
while(true){
frname = prompt("입력하세요");
if(frname == null){
cf = confirm("취소하겠습니까?");
if(cf){
return false;
}
continue;
}
if(frname.trim().length < 1){
alert("입력해라");
continue;
}
break;
}
idx = fr.indexOf(frname);
str = `찾는이름: ${frname}<br>`
if(idx < 0){
str += "그런건없다."
}else{
str += idx + "번째에 있습니다.";
}
document.getElementById('result1').innerHTML=str;
}
proc2 = () => {
while(true){
frname = prompt("입력하세요");
if(frname==null){
cf = confirm("취소하겠습니까?");
if(cf){
return false;
}
continue;
}
if(frname.trim().length <1){
alert("입력해라");
continue;
}
break;
}
idx = fr.lastIndexOf(frname);
str = `찾는이름: ${frname}<br>`
if(idx < 0){
str += "그런건없다."
}else{
str += idx + "번째에 있습니다.";
}
document.getElementById('result2').innerHTML=str;
}
proc3 = function(){
frname = prompt("입력하세요");
idx= 0;
str="찾는 이름: "+frname+"<br>";
while(true){
idx = fr.indexOf(frname, idx);
if(idx<0){
str +="더이상 존재하지 않습니다.";
break;
}
str += idx+"번째, "
idx++;
}
document.getElementById('result3').innerHTML= str;
}
</script>
</head>
<body>
<h3>Array메소드</h3>
<div class="box">
fr = ["사과", "바나나", "참외","사과","복숭아","사과","파인애플"]<br>
indexOf(item,start) : 첫번째 item을 찾는다.<br>
lastIndexOf(item,start): 마지막 item을 찾는다.<br>
start매개변수는 생략 가능, 찾을 시작 위치를 지정한다.
<br>
<button type="button" onclick="proc1()">indexOf</button>
<button type="button" onclick="proc2()">lastIndexOf</button>
<button type="button" onclick="proc3()">indexOf_start</button>
<div id="result1"></div>
<div id="result2"></div>
<div id="result3"></div>
</div>
</body>
</html>