JavaScript 的 数组查找方法

等级 4282 次按键

这使用find获取元素,使用findIndex获取其位置。

JavaScript 代码

// 用户对象数组
1const users = [
2 { id: 1, name: "Alice", active: true },
3 { id: 2, name: "Bob", active: false },
4 { id: 3, name: "Carol", active: true }
5];
6
// find()返回第一个匹配条件的元素
// 如果没有匹配则返回undefined
7const found = users.find(u => u.id === 2);
// found是{ id: 2, name: "Bob", active: false }
8console.log(found.name);
9
// findIndex()返回第一个匹配元素的索引
// 如果没有匹配则返回-1
10const index = users.findIndex(u => u.name === "Carol");
// Carol在索引2
11console.log(index);

运行结果

Bob
2
用这段代码练习打字

可以用这段代码练习打字。成绩不会计入排行榜。

这段代码中的符号

这段 JavaScript 代码中需要输入的符号及其出现次数。

  • =× 11
  • :× 9
  • ,× 8
  • "× 8
  • .× 7
  • ;× 5
  • (× 4
  • )× 4
  • {× 3
  • }× 3

JavaScript 等级 4 的更多代码示例

← 返回 JavaScript 打字练习