封装一个函数, 查看数字在数组中是否出现过, 如果出现过就返回数字在数组中的位置,没有出现过返回-1;

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
//封装一个函数, 查看数字在数组中是否出现过, 如果出现过就返回数字在数组中的位置,没有出现过返回-1;
//实例: console.log(indexOf(1, [1, 2, 3, 4, 5])) 返回结果: 0;
//console.log(indexOf(6, [1, 2, 3, 4, 5])) 返回结果: -1;
function indexOf(iNum, arr){
for(var i = 0; i < arr.length; i++){
if(iNum === arr[i]){
return i;
}else {
return -1
}
}
}

console.log( indexOf(1, [1, 2, 3, 4, 5]) );
console.log( indexOf(6, [1, 2, 3, 4, 5]) );

</script>
</head>
<body>

</body>
</html>

猜你喜欢

转载自www.cnblogs.com/yxs1530/p/10242443.html
今日推荐