检查数组中的元素 [英] Check for element in array

查看:74
本文介绍了检查数组中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检查数组中是否已经存在元素。我至少知道两种不同的方式: [1] [2]

I'm trying to check if an elements already exists in an array. I know of at least 2 different ways to do so: [1] and [2].

我同时测试了两个,但没有得到 在两种情况下:

I tested both of them, but get no in both cases:

var myArray = ["Banana", "Orange", "Apple", "Mango"];

if ("Banana" in myArray) {
  console.log("yes")
} else {
  console.log("no") // <--
}

if (typeof myArray["Banana"] === 'undefined') {
  console.log("no") // <--
} else {
  console.log("yes")
}

在两种情况下我都得到。我错过了什么吗?

In both cases I get no. Am I missing something?

还有,哪个更快?

这是一个小提琴

推荐答案

两者都在做几乎相同的事情:检查 myArray 是否具有名为 Banana 的属性,不它具有键 0,1,2, 3 ,并且值为 myArray [ 0] 恰好是香蕉。

Both of those are doing the almost the same thing: Checking if myArray has a property called "Banana", which it doesn't; it has keys 0,1,2, and 3, and the value at myArray[0] happens to be "Banana".

如果要检查字符串是否在数组中,可以使用 Array.prototype.indexOf

If you want to check if a string is in an array you can use Array.prototype.indexOf:

if( myArray.indexOf("Banana") >= 0 ) {
  console.log("yes")
} else {
  console.log("no")
}

这篇关于检查数组中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆