包含和hasOwnProperty在JS中的数组搜索中的区别



在时间和空间复杂度方面,在JS中搜索Array中的元素的includeshasOwnProperty有什么区别?

两者都可用于查找元素是否存在于Array中。

hasOwnProperty返回一个布尔值,该值指示要调用它的对象是否具有具有参数名称的属性以及作为每个人includes()方法确定字符串是否包含指定字符串的字符。 如果字符串包含字符,则 include 方法返回 true;如果不包含字符,则返回 false。此外,它区分大小写。

最后,我认为这个问题是基于一个错误的假设。

两者都可用于查找元素是否存在于数组中。

不對。includes检查数组中的任何元素是否与参数匹配。hasOwnProperty检查数组是否具有与参数匹配的属性

$ const array = ['test', 'another'];
$ array.includes('test')
true
$ array.hasOwnProperty('test')
false
$ array.includes('length')
false
$ array.hasOwnProperty('length')
true

您可以看到includeshasOwnProperty返回的结果不同,因此比较效率毫无意义。

includes检查数组是否包含指定的值,而hasOwnProperty检查数组是否在其__proto__中指定了属性名称:

const arr = [1, 2, 3];
arr.prop = 'Some prop';
arr.includes(2); // -> true
arr.hasOwnProperty(2); // -> false
arr.includes('prop'); // -> false
arr.hasOwnProperty('prop'); // -> true

最新更新