Skip to content

Instantly share code, notes, and snippets.

@jacobedawson
Forked from anonymous/index.html
Last active May 17, 2016 19:00
Show Gist options
  • Save jacobedawson/daad8d5a5645580ec0896e24189e7238 to your computer and use it in GitHub Desktop.
Save jacobedawson/daad8d5a5645580ec0896e24189e7238 to your computer and use it in GitHub Desktop.
JS - indexOf - JS Bin// source http://jsbin.com/puqago
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script id="jsbin-javascript">
//indexOf
var x = [2,5,6,6];
//second parameter is the from index (inclusive)
x.indexOf(6,-1);//3
//-1 can be used to grab the last item in an array
var indices = [];
var array = ['a','b','a','c','a','d'];
var element = 'a';
var idx = array.indexOf(element);//0
while (idx != -1) {//while there is an element returned
//we grab the first occurence if it exists
//then push the returned element's index into a cache array
indices.push(idx);
//we then increment by telling indexOf to search starting from
//the next index
idx = array.indexOf(element,idx+1);
//this function will keep running until all element indicies are found
}
console.log(indices);//[0,2,4];
</script>
<script id="jsbin-source-javascript" type="text/javascript">//indexOf
var x = [2,5,6,6];
//second parameter is the from index (inclusive)
x.indexOf(6,-1);//3
//-1 can be used to grab the last item in an array
var indices = [];
var array = ['a','b','a','c','a','d'];
var element = 'a';
var idx = array.indexOf(element);//0
while (idx != -1) {//while there is an element returned
//we grab the first occurence if it exists
//then push the returned element's index into a cache array
indices.push(idx);
//we then increment by telling indexOf to search starting from
//the next index
idx = array.indexOf(element,idx+1);
//this function will keep running until all element indicies are found
}
console.log(indices);//[0,2,4];
</script></body>
</html>
//indexOf
var x = [2,5,6,6];
//second parameter is the from index (inclusive)
x.indexOf(6,-1);//3
//-1 can be used to grab the last item in an array
var indices = [];
var array = ['a','b','a','c','a','d'];
var element = 'a';
var idx = array.indexOf(element);//0
while (idx != -1) {//while there is an element returned
//we grab the first occurence if it exists
//then push the returned element's index into a cache array
indices.push(idx);
//we then increment by telling indexOf to search starting from
//the next index
idx = array.indexOf(element,idx+1);
//this function will keep running until all element indicies are found
}
console.log(indices);//[0,2,4];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment