首页 > 解决方案 > indexOf 是否比尝试索引对象慢?

问题描述

我对性能一无所知。但是,如果someArray.includes(someString)必须搜索整个数组,尝试查找对象的索引会更直接(因此更快,代码也更少)?

// create an array of number strings
const arr = Array(100).from(n => n.toString());

// find whether a string is in the array
const isStringInArr_includes_true = arr.includes("50"); // true
const isStringInArr_includes_false = arr.includes("500"); // true

// instead of creating an array, create an object with the array items as keys
// EDIT: actually you can just use the array itself
// and look up the string as a key
const isStringInArr_lookup_true = !!arr["50"]; // !!("50") === true
const isStringInArr_lookup_false = !!arr["500"]; // !!(undefined) === false

显然,这只适用于字符串数组。

标签: javascriptarrays

解决方案


推荐阅读