如何创建自定义查找方法?
How to create custom find method?
我正在尝试使用 Array.prototype
创建自定义查找方法,我尝试了很多方法,但我无法打破第一个匹配项的循环:
let arr = ["Bill", "Russel", "John", "Tom", "Eduard", "Alien", "Till"];
Array.prototype.myFind = function (callback) {
for (let i = 0; i < this.length; i++) {
callback(this[i], i, this);
}
};
arr.myFind((element, index, array) => {
if (element[0] === "T") {
console.log(`This is ${element} in index of ${index} in array ${array}`);
}
});
那么现在你只有一个 for 循环,如果你想找到任何满足条件的元素,你必须 return 来自回调的布尔值和 return 元素,因为returned 布尔值是 true
。如果你想要找到的元素的索引和初始数组也被 returned,你可以 return 一个对象并解构它:
let arr = ["Bill", "Russel", "John", "Tom", "Eduard", "Alien", "Till"];
Array.prototype.myFind = function (callback) {
for (let i = 0; i < this.length; i++) {
if ( true == callback(this[i], i, this)) {
return {element:this[i],index:i,array:this};
}
}
};
let {element,index,array} = arr.myFind((element) => element[0] === "T");
console.log(`This is ${element} in index of ${index} in array ${array}`);
我正在尝试使用 Array.prototype
创建自定义查找方法,我尝试了很多方法,但我无法打破第一个匹配项的循环:
let arr = ["Bill", "Russel", "John", "Tom", "Eduard", "Alien", "Till"];
Array.prototype.myFind = function (callback) {
for (let i = 0; i < this.length; i++) {
callback(this[i], i, this);
}
};
arr.myFind((element, index, array) => {
if (element[0] === "T") {
console.log(`This is ${element} in index of ${index} in array ${array}`);
}
});
那么现在你只有一个 for 循环,如果你想找到任何满足条件的元素,你必须 return 来自回调的布尔值和 return 元素,因为returned 布尔值是 true
。如果你想要找到的元素的索引和初始数组也被 returned,你可以 return 一个对象并解构它:
let arr = ["Bill", "Russel", "John", "Tom", "Eduard", "Alien", "Till"];
Array.prototype.myFind = function (callback) {
for (let i = 0; i < this.length; i++) {
if ( true == callback(this[i], i, this)) {
return {element:this[i],index:i,array:this};
}
}
};
let {element,index,array} = arr.myFind((element) => element[0] === "T");
console.log(`This is ${element} in index of ${index} in array ${array}`);