Is the Javascript String length constant time?

后端 未结 6 2155
萌比男神i
萌比男神i 2020-12-18 20:15

I\'m fairly new to JS, and realize length is considered a property. But I received a comment to not use str.length in a loop:

for (i=0; i

6条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-18 20:56

    The question seems to have been well answered, but here's another 2¢ which may be helpful.

    Using string.length can cause unexpected behavior in for loops if the string is overwritten by something with a different length inside the loop e.g:

    var k = "abcabcabc";
    for(var i=0; i

    Will log "abcabcab", "abcabca", ... , "abca" and then stop because the length is changing.

    Of course, this may be intentional, in which case go for it (although arguably you should use a while loop).

提交回复
热议问题