Immutable.List

List is the immutable version of JavaScript's array structure.

  1. let movies = Immutable.fromJS([ // again use fromJS for deep immutability
  2. {
  3. name: 'The Fellowship of the Ring',
  4. released: 2001,
  5. rating: 8.8
  6. },
  7. {
  8. name: 'The Two Towers',
  9. released: 2002,
  10. rating: 8.7
  11. }
  12. ]);
  13. movies = movies.push(Immutable.Map({
  14. name: 'The Return of the King',
  15. released: 2003
  16. }));
  17. movies = movies.update(2, movie => movie.set('rating', 8.9)); // 0 based
  18. movies = movies.zipWith(
  19. (movie, seriesNumber) => movie.set('episode', seriesNumber),
  20. Immutable.Range(1, movies.size + 1) // size property instead of length
  21. );
  22. console.log(movies);
  23. /* writes
  24. List [
  25. Map { "name": "The Fellowship of the Ring", "released": 2001, "rating": 8.8, "episode": 1 },
  26. Map { "name": "The Two Towers", "released": 2002, "rating": 8.7, "episode": 2 },
  27. Map { "name": "The Return of the King", "released": 2003, "rating": 8.9, "episode": 3 } ]
  28. */

Here we use the Immutable.fromJS call again since we have objects stored in the array. We call push to add items to the list, just like we would call it on an array. But since we're creating a new copy, we must rebind the variable. We have the same set and update calls when we want to update items at specific indexes. We also have access to array functions like map, reduce with support for extras like the one we're using here, zipWith.

原文: https://angular-2-training-book.rangle.io/handout/immutable/immutable-js/lists.html