var folks = [{
name: "Nill",
age: "20",
occupation: "delinquent"
}, {
name: "John",
age: "3",
occupation: "delinquent"
}, {
name: "Bob",
age: "32",
occupation: "developer"
}, {
name: "Bill",
age: "17",
occupation: "delinquent"
}, {
name: "Bob",
age: "40",
occupation: "yes"
}]
var i;
let start1 = Date.now();
const b1 = folks.map(fella => {
if (fella.name == "Bob") {
i = fella
}
})
console.log(i)
let timeTaken2 = Date.now() - start1;
console.log("Total time taken map : " + timeTaken1 + " milliseconds");
var start2 = Date.now();
const a = folks.find(fella => fella.name === "Bob")
console.log(a)
var timeTaken2 = Date.now() - start2;
console.log("Total time taken find : " + timeTaken2 + " milliseconds");
let start3 = Date.now();
const b = folks.filter(fella => fella.name === "Bob")
console.log(b)
let timeTaken3 = Date.now() - start3;
console.log("Total time taken : " + timeTaken3 + " milliseconds");
对于 JavaScript 中的
map()
、filter()
或 find()
哪个更快的问题,最简单的答案是 find()
。
原因如下:
想象一下你正在玩捉迷藏。地图会检查每个藏身点,即使它立即找到你要找的人。过滤器也会遍历每一个可能的地方,确保没有一个人掉队。但找到是最快的。一旦找到人,它就会停止寻找。因此,如果您只需要第一个匹配项,请使用 find。它不会浪费时间,而且很快就能得到结果。