[SERVER-10916] Iterating over string using for..in produces some methods Created: 26/Sep/13  Updated: 05/Apr/17  Resolved: 03/May/16

Status: Closed
Project: Core Server
Component/s: JavaScript
Affects Version/s: 2.4.6
Fix Version/s: None

Type: Bug Priority: Minor - P4
Reporter: Jaromir Obr Assignee: Mira Carey
Resolution: Done Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Ubuntu 13.04 x86_64


Backwards Compatibility: Fully Compatible
Operating System: Linux
Steps To Reproduce:

> str = "Mongo"
Mongo
> for (var c in str)

{ print(c) }

Expected result:
0
1
2
3
4

Actual result:
0
1
2
3
4
ltrim
rtrim
startsWith
endsWith
pad


I also tested it with the native V8 version 3.21.4 or with JavaScript in Chrome. It's working well there.

Sprint: Platforms 13 (04/22/16), Platforms 14 (05/13/16)
Participants:

 Comments   
Comment by Mira Carey [ 03/May/16 ]

This is working as designed. We inject methods onto the string prototype in the shell and make no special effort to mark them as specifically non-enumerable.

If you'd like to enumerate only the keys actually on the string, you can use getOwnPropertyNames(), or you can check values with hasOwnProperty() inside of your loop.

I.e.

for (var c in str) {
  if (str.hasOwnProperty(c)) {
    print(c);
  }
}

Generated at Thu Feb 08 03:24:23 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.