开发者

JavaScript -What's with the #2 in this program

开发者 https://www.devze.com 2023-02-14 02:03 出处:网络
According to the tutorial I am reading, the program below displays \"Hello Ima Reader.\" I have one question about this program. Why does it, in its final line, insert a \"2\" into alert(name[2])?

According to the tutorial I am reading, the program below displays "Hello Ima Reader."

I have one question about this program. Why does it, in its final line, insert a "2" into alert(name[2])?

When the function is called in the second last line, it only passes "name", but when the alert is run it uses a "2". I'm assuming that 2 refers to the length of name, but is it necessary? If so, Why?

function makeHello(name) {
   name[name.length] = "Hello" + name [0] + " " + na开发者_JS百科me[1];
}

var name = new Array ('Ima', 'Reader');
makeHello(name);
alert(name[2]); 


makeHello adds a new item to the array "name". This new item is the word "Hello" plus the first and second item in the array. Therefore, makeHello[2] returns "Hello Ima Reader".

makeHello is trying to add the new item to the end of the array. If you don't know the size of the array then you can call name.length to return a value which will symbolize the position of the new/last item.


The line var name = new Array ('Ima', 'Reader'); creates an array called name with element 0 set to "Ima" and element 1 set to "Reader".

The next line, makeHello(name);, invokes the makeHello function which creates an element 2 in the name array set to "Hello Ima Reader".

The last line, alert(name[2]); merely displays the element 2 that was created by the makeHello function.


This code is doing some convoluted stuff. The makeHello(name) call passes a 2-element array to the makeHello() function. At this point, hello looks like this:

['Ima', 'Reader']

The makeHello function reads the first two elements from the array that's passed in, but does not change them, and uses them to insert a new element at the end of the array. When makeHello is done, hello looks like this:

['Ima', 'Reader', 'Hello Ima Reader']

The alert() call simply grabs the last element from the hello array.


Overall, this code uses fairly poor style, and I might recommend using a better tutorial to learn JavaScript from. The Mozilla Dev Center is a top-notch resource for all things JS.


The 2 refers to the 3rd position in the name array, which was set in the makeHello function.

0

精彩评论

暂无评论...
验证码 换一张
取 消