javascript 如何检查数组索引是否存在?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15734320/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 01:53:40  来源:igfitidea点击:

How to check if an array index exist?

javascript

提问by gipouf

I'm trying to check whether an array index exist in TypeScript, by the following way (Just for example):

我正在尝试通过以下方式检查 TypeScript 中是否存在数组索引(例如):

var someArray = [];

// Fill the array with data

if ("index" in someArray) {
   // Do something
}

However, i'm getting the following compilation error:

但是,我收到以下编译错误:

The in operator requires the left operand to be of type Any or the String primitive type, and the right operand to be of type Any or an object type

in 运算符要求左操作数为 Any 类型或 String 基本类型,右操作数为 Any 类型或对象类型

Anybody knows why is that? as far as I know, what I'm trying to do is completely legal by JS.

有谁知道这是为什么?据我所知,我正在尝试做的对于 JS 来说是完全合法的。

Thanks.

谢谢。

回答by metadept

As the comments indicated, you're mixing up arrays and objects. An array can be accessed by numerical indices, while an object can be accessed by string keys. Example:

正如评论所示,您正在混淆数组和对象。数组可以通过数字索引访问,而对象可以通过字符串键访问。例子:

var someObject = {"someKey":"Some value in object"};

if ("someKey" in someObject) {
    //do stuff with someObject["someKey"]
}

var someArray = ["Some entry in array"];

if (someArray.indexOf("Some entry in array") > -1) {
    //do stuff with array
}

回答by Travis J

jsFiddle Demo

jsFiddle 演示

Use hasOwnPropertylike this:

hasOwnProperty像这样使用:

var a = [];
if( a.hasOwnProperty("index") ){
 /* do something */  
}

回答by abahet

You can also use the findindex method :

您还可以使用 findindex 方法:

var someArray = [];

if( someArray.findIndex(x => x === "index") >= 0) {
    // foud someArray element equals to "index"
}