Array.from(arrayLike) và [...arrayLike] đều tạo array từ iterable.
- Array.from() mạnh hơn: nhận array-like không phải iterable (chỉ cần có
lengthvà indexed elements) và có tham sốmapFnđể transform ngay khi tạo. - Spread yêu cầu đúng iterable protocol.
javascript
// NodeList không phải true iterable trong mọi môi trường
Array.from(document.querySelectorAll('div')); // OK
// mapFn: tạo mảng 1-5 ngay lập tức
Array.from({ length: 5 }, (_, i) => i + 1); // [1, 2, 3, 4, 5]Array.from(arrayLike) and [...arrayLike] both create arrays from iterables.
- Array.from() is more powerful: it accepts array-like objects that are not iterable (requiring only
lengthand indexed elements) and has amapFnparameter to transform while creating. - Spread requires the proper iterable protocol.
javascript
// NodeList may not be a true iterable in all environments
Array.from(document.querySelectorAll('div')); // OK
// mapFn: create array 1-5 inline
Array.from({ length: 5 }, (_, i) => i + 1); // [1, 2, 3, 4, 5]