手写 some
文章目录
手写 some
some()方法测试数组中是不是至少有 1 个元素通过了被提供的函数测试。它返回的是一个 Boolean 类型的值。
-
callback
用来测试每个元素的函数,接受三个参数:- element
数组中当前正在处理的元素。 - index 可选
正在处理的元素在数组中的索引。 - array 可选
调用了 filter 的数组本身。 - thisArg 可选
执行 callback 时,用于 this 的值。
- element
Array.prototype.some = function(fn) {
if (typeof fn !== "function") {
throw "参数必须为函数";
}
//get array going to be iterated
let arr = this;
if (!Array.isArray(arr)) {
throw "只能对数组使用some方法";
}
for (let index = 0; index < arr.length; index++) {
let invokedReturn = fn(arr[index], index, arr);
if (invokedReturn) {
return true;
}
}
return false;
};
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论