Javascript Data Type How to - Retrieve array values using indexOf








Question

We would like to know how to retrieve array values using indexOf.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
var arr = ['hello', 'hi', 'good morning', 'sweet', 'cool', 'nice', 'a!', 'how are you?', 'Thanks!'];
var start = arr.indexOf('good morning'),
    ends  = arr.indexOf('hey!');
for (var i=start; i<ends; i++) {
    document.writeln(arr[i]);
    document.writeln('<br/>');
}<!--   www  .j  a v a 2  s.  c  o m-->
document.writeln('<br/>');
document.writeln('<br/>');
arr = ['hello', 'hi', 'good morning', 'sweet', 'cool', 'nice', 'a!', 'how are you?', 'Thanks!'];
arr.slice(arr.indexOf('good morning'), arr.indexOf('hey!')).forEach(function(s) {
    document.writeln(s)
    document.writeln('<br/>');
});
</script>
</head>
<body>
</body>
</html>

The code above is rendered as follows: