Javascript, Getting Length of String Held in Array - Stack Overflow

k = [['a'], ['ab'], ['abc']];alert(k[2].length);The above code fragment

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?

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?

Share Improve this question asked Aug 14, 2012 at 21:56 user1541722user1541722 391 gold badge2 silver badges4 bronze badges 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? – Felix Kling Commented Aug 14, 2012 at 21:58
  • Maybe a reading a Javascript Array Tutorial will help. – BryanH Commented Aug 15, 2012 at 5:43
Add a ment  | 

2 Answers 2

Reset to default 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)

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);​

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1740975456a4284955.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信