I understand the basic structure of a For loop in JavaScript. I was looking at the following example:
function howMany(selectObject) {
var numberSelected = 0;
for (var i = 0; i < selectObject.options.length; i++) {
if (selectObject.options[i].selected) {
numberSelected++;
}
}
return numberSelected;
}
On the Fourth line I don't understand what you would call the
[i]
in terminology and why it is square brackets?
I understand the basic structure of a For loop in JavaScript. I was looking at the following example:
function howMany(selectObject) {
var numberSelected = 0;
for (var i = 0; i < selectObject.options.length; i++) {
if (selectObject.options[i].selected) {
numberSelected++;
}
}
return numberSelected;
}
On the Fourth line I don't understand what you would call the
[i]
in terminology and why it is square brackets?
- 5 You never saw an array ? – Denys Séguret Commented Nov 10, 2015 at 12:51
- Get value in array at position i – Joakim M Commented Nov 10, 2015 at 12:51
- w3schools./js/js_arrays.asp – Joakim M Commented Nov 10, 2015 at 12:52
-
1
selectObject
is anobject
havingarray
propertyoptions
. now thisarray
containsobjects
, having one propertyselected
– ozil Commented Nov 10, 2015 at 12:53 -
2
I know them as
indexer
's – Johan Commented Nov 10, 2015 at 13:09
4 Answers
Reset to default 7[]
is a way of selecting a property from an object given a specific key
, in this case the key (or index
) is i
and the object is an array
. In an array an index can go from 0 to the length of the array - 1.
In an object a key is the name of any property within that object. For example, you can also select the value of the property key selected
from the object selectObject.options[i]
by using the following: selectedObject.options[i]['selected']
.
As an alternative to your for loop
, you could use a for in loop
. Which works on objects (and arrays).
for (var key in selectObject.options) {
if (selectObject.options[key].selected) {
numberSelected++;
}
}
the [i]
is used to address variables in for example an array.
Lets say you have an array names containing sarah
and john
. names[0]
would return sarah
.
What your for loop does is go over all the entries in selectObject.options and looks at the value of selected (most likely a true/false).
selectObject.options returns an array
, and the [ ]
, is the way to get an element from the array, using its index (the i
in your case)
Say you had an array of strings like so:
var arr = ["this", "is", "an", "array", "of", "strings"];
and you want to access one of the array's elements, you would:
console.log(arr[5]); // prints "strings" to the console
function howMany(selectObject) {
var numberSelected = 0;
for (var i = 0; i < selectObject.options.length; i++) {
if (selectObject.options[i].selected) {
numberSelected++;
}
}
return numberSelected;
}
In this above code why is numberSelected, and in the coditional statement numberSelected++