javascript 如何在数组索引中传递变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4811018/
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-25 14:57:00  来源:igfitidea点击:

How to pass a variable in array index

javascriptarraysindexing

提问by menardmam

i repeat the title because everything is there : How to pass a variable in array index

我重复标题,因为一切都在那里:如何在数组索引中传递变量

var xyz = 0;
var somearray = ['a','b','c'];
var content = somearray[xyz]; - **that dont work !**

what should be the RIGHT way to do that ?

这样做的正确方法应该是什么?

采纳答案by Joe Zitzelberger

That actually is correct. After executing your code, minus the comment, content contains 'a'.

这其实是正确的。执行代码后,减去注释,内容包含“a”。

<html>
<head>
   <title>Test</title>
</head> 
<body>
<script type="text/javascript"> 
    var xyz = 0;
    var somearray = ['a','b','c'];
    var content = somearray[xyz];
    alert(content);
</script>
</body>
</html>

You should get a nice little alert box that says "a".

你应该得到一个漂亮的小警告框,上面写着“a”。

回答by Oddlyeven

Just a stab in the dark here, but perhaps the OP is using inArray and might be asking (indirectly) how to get the intellisense working in whatever tool they're using.

只是在这里暗中刺伤,但也许 OP 正在使用 inArray 并且可能会(间接地)询问如何让智能感知在他们使用的任何工具中工作。

If that's the case, I'm sure someone here can provide a more elegant solution but something similar to the following should work:

如果是这种情况,我相信这里有人可以提供更优雅的解决方案,但类似于以下内容的方法应该可行:

var somearray = ['a','b','c'];
var index = $.inArray('a', somearray);
if (index > -1) {
    index = isNaN(index) ? 0 : index;
    var content = somearray[index];
}