use*_*203 5 javascript arrays element
我对这个任务有点困惑我有这样一个数组:array = ["123","456","#123"]我想找到包含#的元素.我用过array.includes("#"),array.indexOf("#")但它没有工作任何想法?
Tai*_* Le 19
因为includes会将'#'与每个数组元素进行比较.
var array = ["123", "456", "#123"];
var el = array.find(a =>a.includes("#"));
console.log(el)Run Code Online (Sandbox Code Playgroud)
ggo*_*len 18
由于标题和帖子正文不同,这里似乎有多个问题。您想知道数组是否有元素还是想获取元素本身?如果你想获取一个元素,你想要哪个(哪些)——第一次出现、最后一次出现还是所有出现的数组?
这篇文章旨在为未来的访问者提供资源,这些访问者可能不一定想要find(即返回与谓词匹配的数组开头的第一个元素),如最上面的答案所示。为了详细说明这个答案,有一个问题是在布尔上下文中不加区别地替换some为find- 返回的元素可能是错误的,如
if ([5, 6, 0].find(e => e < 3)) { // fix: use `some` instead of `find`
console.log("you might expect this to run");
}
else {
console.log("but this actually runs " +
"because the found element happens to be falsey");
}Run Code Online (Sandbox Code Playgroud)
请注意,e => e.includes("#")可以用任何谓词替换,因此它在很大程度上与问题无关。
indexOf当在条件中使用并且未能考虑到 0(在数组中的第一个位置找到该元素)为假这一事实时,可能会出现相同的问题。
const array = ["123", "456", "#123"];
console.log(array.some(e => e.includes("#"))); // true
console.log(array.some(e => e.includes("foobar"))); // falseRun Code Online (Sandbox Code Playgroud)
const array = ["123", "456", "#123"];
console.log(array.every(e => e.includes("#"))); // false
console.log(array.every(e => /\d/.test(e))); // trueRun Code Online (Sandbox Code Playgroud)
const array = ["123", "456", "#123", "456#"];
console.log(array.find(e => e.includes("#"))); // "#123"
console.log(array.find(e => e.includes("foobar"))); // undefinedRun Code Online (Sandbox Code Playgroud)
const array = ["123", "456", "#123", "456#"];
console.log(array.findIndex(e => e.includes("#"))); // 2
console.log(array.findIndex(e => e.includes("foobar"))); // -1Run Code Online (Sandbox Code Playgroud)
MDN:Array.prototype.findIndex()
const array = ["123", "456", "#123", "456#"];
console.log(array.filter(e => e.includes("#"))); // ["#123", "456#"]
console.log(array.filter(e => e.includes("foobar"))); // []Run Code Online (Sandbox Code Playgroud)
const array = ["123", "456", "#123", "456#"];
console.log(array.findLast(e => e.includes("#"))); // "456#"
console.log(array.findLast(e => e.includes("foobar"))); // undefinedRun Code Online (Sandbox Code Playgroud)
MDN:Array.prototype.findLast()
const array = ["123", "456", "#123", "456#"];
console.log(array.findLastIndex(e => e.includes("#"))); // 3
console.log(array.findLastIndex(e => e.includes("foobar"))); // -1Run Code Online (Sandbox Code Playgroud)
MDN:Array.prototype.findLastIndex()
const filterIndices = (a, pred) => a.reduce((acc, e, i) => {
pred(e, i, a) && acc.push(i);
return acc;
}, []);
const array = ["123", "456", "#123", "456#"];
console.log(filterIndices(array, e => e.includes("#"))); // [2, 3]
console.log(filterIndices(array, e => e.includes("foobar"))); // []Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12674 次 |
| 最近记录: |