[英]How can i define this peice of code inside arrow function, i want to use the iterating arrayElement?
我希望函数能够输出真或假,如果数组中存在 searchElement,它应该返回真或假。 我知道我可以使用简单的 for 循环和 if-else 组合,但我想使用箭头函数。
我知道默认情况下 'includes' 函数存在于 js 中,我正试图创建一个类似于它的函数,这就是我不想使用它的原因
const somestuff=[1,2,54,23,65,132,76,'A','wth','Health is Wealth'];
function includes(array,searchElement){
const result=somestuff.filter(arrayElement=> arrayElement===searchElement)
if(arrayElement===searchElement){
console.log('true');
}
else{
console.log('false');
}
}
includes(somestuff,65);
仅这一行就为我提供了 arrayElement,我希望它返回 true 或 false,这就是为什么我尝试了 if else 语句,但我不知道如何在箭头函数行中包含该代码块,我认为 == = 应该返回 true 或 false 而不是数字本身,请让我知道我做错了什么,谢谢
const result=somestuff.filter(arrayElement=> arrayElement===searchElement)
这可以用 find 函数而不是过滤器来实现。
现场演示: https : //replit.com/@kallefrombosnia/PalatableStingySphere#index.js
// Define function
const includes = (array, element) =>{
return array.find(item => item === element) ? true : false;
}
// Log output in console
console.log(includes([1, 2, 3], 4));
const includes = (array, element) =>{ return array.find(item => item === element) ? true : false; } console.log(includes([1, 2, 3], 4));
这个问题的另一个解决方案是使用Array 原型中的一些方法。
const includes = (array, pattern) => {
const comp_function = (element) => element === pattern
return array.some(comp_function)
}
k = [1, 2, 3, 'a', 'b', 'c']
includes(k, 1) // true
includes(k, 'a') // true
includes(k, '1') // false
includes(k, 'd') // false
为什么你必须实施“包括”,
我们有Array.prototype.includes()
规范,所以我们可以做类似的事情
const array1 = [1, 2, 3];
array1.includes(2) // return true
并在此处了解有关规范的更多信息
您可以使用 Array.prototype.find()。 我解释说过滤器是从一些具有相同模式的元素中删除并排列一些元素,但是您可以使用 map() 或 find() 是 ES6 功能,它使我们的生活更轻松。 这个demo会告诉你
// 地图()
const result=somestuff.find(arrayElement=> {
if(arrayElement===searchElement){
console.log('true');
return arrayElement
}
else{
console.log('false');
})
})
// 寻找()
const result=somestuff.find(arrayElement=> arrayElement===searchElement)
最后,我们得到了这个
const somestuff=[1,2,54,23,65,132,76,'A','wth','Health is Wealth'];
function includes(array,searchElement){
const result=somestuff.find(arrayElement=> arrayElement===searchElement)
return result
}
includes(somestuff,65);
这就是我使用您的帮助解决问题的方法
我需要变量 searchElement 存在的位置以及它是否存在的索引。
const exists = (element) => element === searchElement;
console.log(' exists at index: '+somestuff.findIndex(exists) +' therefore: '+somestuff.some(exists));
意味着满足要求的任何值都存储在存在变量中,现在我可以对它们应用数组方法,例如 findIndex() 和 some()
findIndex() 说明值的索引,即使一个值满足要求, some() 也会返回 true
这就是我最初想做的事情:
const somestuff=[1,2,54,23,65,132,76,'A','wth','Health is Wealth'];
const searchElement=54;
const result=somestuff.find(arrayElement=> {
if(arrayElement===searchElement){
console.log('true '+arrayElement);
console.log(somestuff.indexOf(searchElement));}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.