0

I have an array as follows:

var str_array=["hello","world"]

How to get length of string when string are there in array? I just want to get length of string "hello" and then "world" inside a loop. This is what I've tried:

for (var i=0; i<= str_array[0].length; i++){
  alert(str_array[i].starAt(i)); 
 }     

I get error message

TypeError: Cannot read property 'length' of undefined
0

2 Answers 2

2

Try this:

var str_array = ["hello", "world"];
for (var i = 0, len = str_array.length; i < len; i++) {
  alert('Length of ' + str_array[i] + ' is ' + str_array[i].length);
}

Sign up to request clarification or add additional context in comments.

2 Comments

Its a variable, used just for optimization purpose. I dont want length to be calculate every time loop is iterated..
can you help me to directly analyzing my code in this forum coderbyte.com/CodingArea/… actually i am trying to finish number 4 challenges to make simple encryption with my own algorhytm?
1

How about this:

str_array.forEach(function(e){ alert("Length = " + e.length) });

You could also use map to get the length out of each element:

var lengths = str_array.map(function(e){ return e.length });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.