3

Why & ldquo; array.length & rdquo; returns the array object when we put...

 2 years ago
source link: https://www.codesd.com/item/why-array-length-returns-the-array-object-when-we-put-it-in-array.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Why & ldquo; array.length & rdquo; returns the array object when we put it in array []?

advertisements
rand(array.length)        # returns random index <br>
array[rand(array.length)] # returns random array object

I can't understand the logic behind. I would assume that second example also returns random index and then store it in array.

kitty = [100,102,104,105]

rand(kitty.length)        # returns index, for example 3 ( or 0,1,2 )
array[rand(kitty.length)] # returns random array object, for example 104 ( or 100,102,105)


While array.sample would be the best way to get a random element from an array, I believe OP is asking how the chaining of methods works.

When you call: rand(array.length) a number is returned, true. However in the case of:

array[ rand(array.length) ]

a number is returned but then fed immediately into the array call, which gives you the object at that array index.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK