Skip to content
This repository

each on strings #247

Closed
booo opened this Issue July 14, 2011 · 6 comments

5 participants

Philipp Borgers Jeremy Ashkenas (Soreλ\a) Kit Cambridge Paul Harper
Philipp Borgers
booo commented July 14, 2011

The forEach function works in 1.1.6 on strings. On the current HEAD and the 1.1.7 version each does not work on strings.

_.each("foo",function(x) { console.log(x)})
Jeremy Ashkenas
Owner

_.each has never worked on strings.

Jeremy Ashkenas jashkenas closed this July 14, 2011
Philipp Borgers
booo commented July 14, 2011

Just for the record. It's working in 1.1.6. Perhaps this was never intended but it works! Perhaps you can add this as a feature?

(Soreλ\a)

@jashkenas

Actually, since underscore delegates to the native implementation of JS's functional array utilities, _.each should work on Strings, as they're essentially collections of characters/array-like stuff/whatever.

The thing is that _.each does not do step 1 of Array.prototype.forEach, which is converting the given object to an actual object, which means that x in y when y is a String would fail. And so would y[i] in some engines.

However, Array.forEach.prototype.call("foo", function(x){ console.log(x) }) will log "f", "o" and "o".

tl;dr; if add obj = Object(obj) after if (obj == null) return, it will work :3

Also, http://es5.github.com/#x15.4.4.18

Kit Cambridge

Indices-as-characters in strings don't work in older versions of IE, I'm afraid. While charAt may be used to provide consistent cross-browser iteration over characters, supporting string values in _.each will create a type-checking nightmare.

@booo: Iteration over strings is unsupported in Underscore 1.1.7 due to a change to _.each that adds support for sparse collections. See line 77...the new i in obj check throws an exception when a string is provided, as the in operator doesn't work with primitives.

(Soreλ\a)

@kitgoncharov
Eh, but does converting a string to an object poses the same problem in these old IE engines?

Edit: String object, even.

Paul Harper
var s1 = "asdf";
// These next two should both be an instance of String
var s2 = Object(s1);
var s3 = new String(s1);

// The following statements all return "a" in modern browsers
// In IE7, they all return undefined
// In IE8 the first one returns "a" and the others return undefined
s1[0];
s2[0];
s3[0];

Here's a fiddle.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.