Câu hỏi về việc triển khai hàm "từng" tôi tìm thấy trong mã nguồn underscore.js (nguồn bên dưới).mỗi triển khai trong thư viện underscore.js
Trước tiên, ai đó có thể giải thích dòng "else if (obj.length === + obj.length)" đang kiểm tra.
Thứ hai, ai đó có thể giải thích tại sao hasOwnProperty.call (obj, key) được sử dụng, thay vì obj.hasOwnProperty? Có phải vì thông qua trong obj có thể không thực hiện hasOwnProperty (mà tôi nghĩ mọi đối tượng javascript đã làm)
bất kỳ thông tin chi tiết nào được đánh giá cao. Cảm ơn.
// The cornerstone, an `each` implementation, aka `forEach`.
// Handles objects with the built-in `forEach`, arrays, and raw objects.
// Delegates to **ECMAScript 5**'s native `forEach` if available.
var each = _.each = _.forEach = function(obj, iterator, context) {
if (obj == null) return;
if (nativeForEach && obj.forEach === nativeForEach) {
obj.forEach(iterator, context);
} else if (obj.length === +obj.length) {
for (var i = 0, l = obj.length; i < l; i++) {
if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) return;
}
} else {
for (var key in obj) {
if (hasOwnProperty.call(obj, key)) {
if (iterator.call(context, obj[key], key, obj) === breaker) return;
}
}
}
};
'+ obj.length' là toán tử cộng nhất unary javascript. xem: http://xkr.us/articles/javascript/unary-add/ – mikeycgto
Vì vậy, tuyên bố là một kiểm tra để đảm bảo tài sản dài của obj thực sự là một con số? – user772110
câu lệnh '+ obj.length' chuyển' obj.length' thành một số – mikeycgto