简体   繁体   中英

How are items being added to this javascript array here?

Looking at a beginner's javascript book and trying to understand a small browser program that builds a list with user input. The input box displays and enters strings as input until he just adds " " as an input. Then the list is shown in the browser.

Here's the code:

var userInput = " ";
var namesArray = new Array();

while ( (userInput = prompt("Enter name", " ")) != " ") {
    namesArray[namesArray.length] = userInput;
}

namesArray.sort();

var namesList = namesArray.join("<br />");

var listHolder = document.createElement('div');
var list = listHolder.innerHTML = namesList;
document.body.appendChild(listHolder);

I just don't have understanding of the way the author adds items to the array. Would someone care to explain how namesArray[namesArray.length] = userInput builds an array?

Also here's a fiddle to try it out

Thansk in advance!

Basically .length is the size of the array so .length is the next index of the array without anything in it yet. He just adds the string to the end of the array .length which creates a new position at the end of the array. .length - 1 is the last element of the array so .length would create a new position at the end of the array. The next time through the loop the length will be one greater than the previous time because you added an element to the array.

So what happens is that, we get a while loop that is going to keep asking for a name until we get an empty response:

while ( (userInput = prompt("Enter name", " ")) != " ")

It then uses the length of the inital namesArray to index the new value.

namesArray[namesArray.length] = userInput;

So we know that the array is initially empty. So on the first run the length is going to be zero! We also know that an index of 0 is the first item in an array. So it adds it to the array as the first item. After that, the array now has a length of 1 (since we just added an item). So on the next iteration we add the new item to the array at the index of 1, which increases its length to 2. This goes on forver until we break the while loop.

So if we break it down we'll see it more clearly:

//First iteration

newArray.length = 0;
newArray[newArray.length] = newArray[0]

//Second iteration

newArray.length = 1;
newArray[newArray.length] = newArray[0]

etc.

The condition for the while loop (userInput = prompt("Enter name", " ")) != " ") will remain true as long as a name is entered each time.

Each time a name is entered, the length index is assigned the name. Each time a name is assigned, the length increases. As a result, the array will grow for each name entered.

Normally you could easily add an element to an array via the .push() method. For example:

var ary = []; // empty array
ary.push('foo'); // the ary array now has one element, 'foo'

Now array indices are zero-based, meaning that you refer to the first element as [0], the second as [1], etc. However, the .length property will return the actual number of elements in an array. So if we add 10 elements to our array, asking for the length will give us 10 .

So what the person who wrote that code is doing, is using the fact that the .length property will allow you to target an element of the array that doesn't exist yet -- the element after the last element.

So for example, say we have an array with 10 elements. The length property will be 10, however the index of the last item will be nine, since the indices are zero-based. When the author of that code does:

namesArray[namesArray.length] = userInput;

They're also saying namesArray[10] = userInput; , and assigning userInput to the eleventh spot in the array (remember, zero-index).

Since this can be a little confusing to follow, most programmers will simply use the .push() method, which automatically tacks the value you pass it onto the end of the array without you having to specify an index.

Since arrays are indexed starting from zero, the last element in the array always has the index

namesArray.length - 1

Therefore, the next available unused index is always equal to

namesArray.length

You can safely set values at this index and know that they will be added to the end of the array.

So, you have this array:

var namesArray = new Array();

And you may know you can insert array values like this:

namesAray[0] = 'first value';
namesAray[1] = 'second value';
namesAray[2] = 'third value';

Now, the code is like this:

namesArray[namesArray.length] = userInput;

So, here the namesArray.length brings you the size of the array. Ok, as above you see I've added three values to the namesArray namesArray[0],namesArray[1], namesArray[2] . So the current size of the array is 3 and namesArray[namesArray.length] is equal to namesArray[3] and now here the input value is inserted.

So, like this the code inserts new array value to the end index of array which is checked by while ( (userInput = prompt("Enter name", " ")) != " ") {

Hope you understood.

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