TAILIEUCHUNG - Phát triển Javascript - part 16

Tham khảo tài liệu 'phát triển javascript - part 16', công nghệ thông tin, kỹ thuật lập trình phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả | Objects and Properties 123 Listing Looping arrays with for and for-in TestCase ArrayLoopTest test looping should iterate over all items function var array 1 2 3 4 5 6 var result Standard for-loop for var i 0 l i l i array i assertEquals 123456 test for-in loop should iterate over all items function var array 1 2 3 4 5 6 var result for var i in array array i assertEquals 123456 These two loops both attempt to copy all the elements of one array onto another and then join both arrays into a string to verify that they do indeed contain the same elements. Running this test reveals that the second test fails with the message in Listing . Listing Result of running test in Listing expected 123456 but was 123456function . snip To understand what s happening we need to understand the for-in enumeration. for var property in object will fetch the first enumerable property of object. property is assigned the name of the property and the body of the loop is executed. This is repeated as long as object has more enumerable properties and the body of the loop does not issue break or return if inside a function . Download from 124 Objects and Prototypal Inheritance For an array object the only enumerable properties are its numeric indexes. The methods and the length property provided by are not enumerable. This is why a for-in loop will only reveal the indexes and their associated values for array objects. However when we add properties to an object or one of the objects in its prototype chain they are enumerable by default. Because of this fact these new properties will also appear in a for-in loop as shown by the test failure above. I recommend you don t use for-in on arrays. The problem illustrated above can be worked around as we will see shortly but not without trading off performance. Using for-in on arrays effectively means we can t normalize browser behavior by .

TỪ KHÓA LIÊN QUAN
TAILIEUCHUNG - Chia sẻ tài liệu không giới hạn
Địa chỉ : 444 Hoang Hoa Tham, Hanoi, Viet Nam
Website : tailieuchung.com
Email : tailieuchung20@gmail.com
Tailieuchung.com là thư viện tài liệu trực tuyến, nơi chia sẽ trao đổi hàng triệu tài liệu như luận văn đồ án, sách, giáo trình, đề thi.
Chúng tôi không chịu trách nhiệm liên quan đến các vấn đề bản quyền nội dung tài liệu được thành viên tự nguyện đăng tải lên, nếu phát hiện thấy tài liệu xấu hoặc tài liệu có bản quyền xin hãy email cho chúng tôi.
Đã 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.