איסוף וחזרה, בדרך של ES6

התקן ECMAScript 6 עדיין נמצא בגרסת טיוטה, אבל הוא מבטיח הרבה כלים חדשים ומעניינים שתוכלו להוסיף לארגז הכלים שלכם כמפתחי JavaScript. כיתות חדשות כמו Set ו-Map מציעות פתרונות מקומיים לעבודה עם סוגים ספציפיים של אוספים, והצהרת for...of מספקת אלטרנטיבה אלגנטית לדרכים המסורתיות של איטרציה על נתונים.

באמצעות Set אפשר לעקוב אחרי אוסף פריטים שבהם כל פריט יכול להופיע לכל היותר פעם אחת. באמצעות Map אפשר ליהנות מפונקציונליות רחבה יותר מזו שהיתה זמינה בעבר, באמצעות שימוש ב-Object כדי לשייך מפתחות לערכים. כשמשתמשים ב-Map, המפתחות לא חייבים להיות מחרוזות, ואין צורך לדאוג שבחרתם בטעות שם מפתח שמתנגש עם שמות השיטות של Object. פעולות חיפוש ב-Map וב-Set מקומיים מתבצעות בזמן קבוע, מה שמאפשר שיפורים ביעילות בהשוואה למה שאפשר להשיג באמצעות הטמעות מדומה.

בדוגמה הבאה מוצגת יצירה של Set ושימוש ב-for...of כדי לבצע איטרציה על הרכיבים שלו:

<pre id="log"></pre>

<script>
    function log() {
    document.querySelector('#log').textContent += Array.prototype.join.call(arguments, '') + '\n';
    }

    log('Creating, using, and iterating over a Set:');
    var randomIntegers = new Set();
    // Generate a random integer in the range [1..10] five times,
    // and use a Set to keep track of the distinct integers that were generated.
    for (var i = 0; i < 5; i++) {
    randomIntegers.add(Math.floor(Math.random() * 10) + 1);
    }
    log(randomIntegers.size, ' distinct integers were generated.');
    log('The number 10 was ', randomIntegers.has(10) ? '' : 'not ', 'one of them.');
    log('Here\'s all of them:');
    // Use for...of to iterate over the items in the Set.
    // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-iteration-statements
    // The Set iterator yields a single value corresponding to each entry in the Set.
    for (var item of randomIntegers) {
    log(item);
    }
</script>

הנה דוגמה תואמת שממחישה שימוש ב-Map וחזרה עליו:

<script>
    log('\nCreating and iterating over a Map:');
    // Maps can be initialized by passing in an iterable value (https://people.mozilla.org/~jorendorff/es6-draft.html#sec-map-iterable)
    // Here, we use an Array of Arrays to initialize. The first value in each sub-Array is the new
    // Map entry's key, and the second is the item's value.
    var typesOfKeys = new Map([
    ['one', 'My key is a string.'],
    ['1', 'My key is also a string'],
    [1, 'My key is a number'],
    [document.querySelector('#log'), 'My key is an object']
    ]);
    // You can also call set() to add new keys/values to an existing Map.
    typesOfKeys.set('!!!!', 'My key is excited!');

    // Use for...of to iterate over the items in the Map.
    // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-iteration-statements
    // There are several types of Map iterators available.
    // typesOfKeys.keys() can be used to iterate over just the keys:
    log('Just the keys:');
    for (var key of typesOfKeys.keys()) {
    log('  key: ', key);
    }

    // typesOfKeys.values() can be used to iterate over just the values:
    log('Just the values:');
    for (var value of typesOfKeys.values()) {
    log('  value: ', value);
    }

    // The default Map iterator yields an Array with two items; the first is the Map entry's key and the
    // second is the Map entry's value. This default iterator is equivalent to typesOfKeys.entries().
    log('Keys and values:');
    // Alternative, ES6-idiomatic syntax currently supported in Safari & Firefox:
    // for (var [key, value] of typesOfKeys) { … }
    for (var item of typesOfKeys) {
    log('  ', item[0], ' -> ', item[1]);
    }
</script>

בדפדפנים מסוימים, כמו Chrome, ‏ Internet Explorer ו-Firefox, כבר נוספה תמיכה ב-Set וב-Map. התמיכה המובנית, בשילוב עם ספריות polyfill כמו es6-collections או es6-shim, מאפשרת למפתחי JavaScript להתחיל לפתח כבר היום באמצעות סוגי האוספים החדשים האלה. אין פוליפוילים זמינים להצהרה for...of (אבל אפשר להעביר תמיכה באמצעות Traceur), אבל תמיכה מקורית זמינה היום ב-Chrome וב-Firefox.

עדכון, ספטמבר 2014: קישור לאפשרות נוספת של polyfill, es6-shim