为什么通过键在对象中搜索值比for in在JavaScript中使用搜索要慢?
像这样的代码:
const a = { a: { txt: 1 }, b: { txt: 2 }, c: { txt: 3 }, d: { txt: 4 }, e: { txt: 5 }, f: { txt: 6 } };
console.time('1');
let n = a['e'].txt;
console.log(n, '<<n')
console.timeEnd('1');
console.time('2');
for (const key in a) {
if (a[key].txt == 5) {
const m = a[key];
console.log(m, '<<m')
break;
}
}
console.timeEnd('2');Run Code Online (Sandbox Code Playgroud)
结果是
5'<<通过键'
1:2.329毫秒
{txt:5}'<< for in'
2:0.447ms
这不是很奇怪吗?