google / traceur-compiler

Traceur is a JavaScript.next-to-JavaScript-of-today compiler
Apache License 2.0
8.18k stars 580 forks source link

For-of loops do not work for strings #539

Open heatherleaf opened 10 years ago

heatherleaf commented 10 years ago

For-of loops cannot iterate over strings. E.g., the following code prints "item 1" and "item 2" and then aborts with error "TypeError: Object ABCD has no method 'iterator'"

function for_of_loop(sequence) {
    for (var x of sequence) {
        console.log(x);
    }
}
for_of_loop(["item 1", "item 2"]);
for_of_loop("ABCD");
arv commented 10 years ago

http://people.mozilla.org/~jorendorff/es6-draft.html#sec-string.prototype-@@iterator

heatherleaf commented 10 years ago

I solved it for myself by just copying (and renaming Array to String) the following code from the function polyfillArray to the function polyfillString (in file src/runtime/runtime.js):

defineProperty(Array.prototype, Symbol.iterator, method(function() {
  var index = 0;
  var array = this;
  return {
    next: function() {
      if (index < array.length) {
        return {value: array[index++], done: false};
      }
      return {value: undefined, done: true};
    }
  };
}));
arv commented 10 years ago

This is not compatible with what will be in ES6. See http://mathiasbynens.be/notes/javascript-unicode for more details.

jarek-foksa commented 10 years ago

@arv what about array-like objects such as HTMLCollection, NodeList or NamedNodeMap? Can I use heatherleaf's solution with those objects?

arv commented 10 years ago

@jarek-foksa Most DOM collections will just use ArrayIterator