Practical prototype and scipt.aculo.us part 9

Practical prototype and part 9: The information in this book is distributed on an "as is" basis, without warranty Although every pre-caution has been taken in the preparation of this work, neither the author(s) nor Apress shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in this work. | 36 CHAPTER 3 COLLECTIONS OR NEVER WRITE A FOR LOOP AGAIN Using Enumerable select What if we need to find several needles in a haystack 1 2 3 4 5 6 7 8 9 10 .select isEven - 2 4 6 8 10 Just like detect select tests each item against the given function. But it doesn t stop after the first match it will return all items in the collection that match the criteria. foo 1 bar baz 2 null .select function item return typeof item string - foo bar baz Unlike detect which is guaranteed to return only one item select will always return an array. If there are no matches it will return an empty array. Using Enumerable reject Nearly identical to select reject will return all the items that fail a particular test. 1 2 3 4 5 6 7 8 9 10 .reject isEven - 1 3 5 7 9 Using Enumerable partition When you need to separate a collection into two groups use Enumerable partition. It returns a two-item array the first an array of all items that passed the test and the second an array of all items that failed the test. 1 2 3 4 5 6 7 8 9 10 .partition isEven - 2 4 6 8 10 1 3 5 7 9 Sorting Collections min max and sortBy The next three Enumerable methods min max and sortBy address common situations of arranging collections by value. CHAPTER 3 COLLECTIONS OR NEVER WRITE A FOR LOOP AGAIN 37 Using Enumerable min and max Much like and which identify the smallest and largest values of all the arguments passed to them Enumerable min and max will find the smallest and largest values in an existing group 1 4 9 16 25 - 1 1 4 9 16 25 - 25 var squares 1 4 9 16 25 - 1 - 25 In this example it s easy to figure out what the minimum and maximum values are numbers are directly comparable. For trickier collections though you ll need to pass in a function to identify exactly what you want the maximum or minimum of var words flowers the hate moribund sesquicentennial function word return - 16 function word return - 3

Không thể tạo bản xem trước, hãy bấm tải xuống
TÀI LIỆU MỚI ĐĂNG
Đã phát hiện trình chặn quảng cáo AdBlock
Trang web này phụ thuộc vào doanh thu từ số lần hiển thị quảng cáo để tồn tại. Vui lòng tắt trình chặn quảng cáo của bạn hoặc tạm dừng tính năng chặn quảng cáo cho trang web này.