+ 2
How to find length of an array without using functions in JavaScript and Ruby.
Question Edited I want to know behind the algorithm of arr.length
10 Respostas
+ 9
In Javascript length is a property not a function. In other words it is a variable that is simply returning the value that is held.
In Ruby length or size are both methods. You can achieve something similar by using a for each style loop with a counter variable.
def len(arr)
count = 0
arr.each do
count += 1
end
return count
end
items = [1, 2, 3, 4, 5, 6]
puts len(items)
+ 8
Thanks for editing.
There is no algorithm involved. The length is just an internally stored attribute of the array (in ruby it is a method that returns this attribute). An empty array has length 0. When we add x elements, we add x to the length. When we remove x elements, the length is subtracted by x.
That's it.
+ 8
I agree with @ChaoticDawg
In many languages array length is fixed during compiling time and won't change during runtime.
I'll take the risk of saying that most (if not all) of the dynamic-length data structures that keep track of a length property will follow the simple method i shared before.
+ 6
No, not ALL programming languages follow this. Most OOP languages do something similar, but lower level languages may not or don't have a length function or property at all and you'd need to calculate the value based on the size of the array and the size of the type of an element in the array.
+ 6
This is where getting familiar with MDN for Javascript can come in handy:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length
+ 4
arr.length
Why would you need something else?
Your question is unclear.
+ 2
def len(arr)
count = 0
arr.each do
count += 1
end
return count
end
items = [1, 2, 3, 4, 5, 6]
puts len(any item)
This way
+ 2
Thanks for helping you all.
+ 1
Is that rule follows all programming languages with different implementation.
+ 1
every array has that thing "length" you dont need to understand how it's work its a buit-in peoperity so you can just use it in js like this
array_name.length