简体   繁体   中英

JavaScript For loop with 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?

[] 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++

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM