1
k = [['a'], ['ab'], ['abc']];
alert(k[2].length);

The above code fragment returns 1.

How can I get the length of the string, 3 in this case?

2
  • 2
    You have an array of arrays... is that really what you want? Why don't you just do console.log(k[2]) and see what k[2] is? Commented Aug 14, 2012 at 21:58
  • Maybe a reading a Javascript Array Tutorial will help. Commented Aug 15, 2012 at 5:43

2 Answers 2

9

The object is not what is expected. Consider:

k = [['a'], ['ab'], ['abc']];
a = k[2]    // -> ['abc']
a.length    // -> 1 (length of array)
b = k[2][0] // -> 'abc'
b.length    // -> 3 (length of string)
Sign up to request clarification or add additional context in comments.

1 Comment

Yes. Your array seems a bit off but if you can't control it, @pst's answer is correct. Or you may want to flatten it first so that your code works.
2

In your example, k is not a normal array containing strings. It contains sub-arrays, which contain the strings. You should declare k this way:

k = ['a', 'ab', 'abc'];

If you do want to use your own declaration, you could do this:

alert(k[2][0].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.