如何使用数组元素作为另一个数组的索引

时间:2015-07-11 10:03:15

标签: javascript arrays

我在javascript代码中有两个数组。我想使用数组x的元素作为数组y的索引。

你可以在数组x中看到我的数字,所以我有可能做到这一点的简单方法。

<script>
    var x = [1,2,3,4,6]
    var y = ["kin","kim","jong","ving","gon","von","rick"]
</script>

 y+x[4]  //(not a code just for idea)

必须打印&#34; rick&#34;

我试过

 y+x[4] //I know that's stupid

但它不起作用。请在javascript中提供答案。

3 个答案:

答案 0 :(得分:3)

您应该阅读更多MDN - Array

var x = [1,2,3,4,6]
var y = ["kin","kim","jong","ving","gon","von","rick"]
var index = x[4]; //6
console.log(y[index]); // at index 6, value is "rick"

或者

y[x[4]] // "rick"

答案 1 :(得分:1)

只需将"require": { "sorien/silex-pimple-dumper": "~1.0" } 作为索引传递给x[4]  即y,输出&#34; rick。&#34;

答案 2 :(得分:0)

我会使用其他类型的数据结构,哈希值存储键值对并适合您的使用:

var x = { 0: "Kin",
          1: "kim",
          2: "jong",
          3: "vin",
          4: "gon",
          5: "von",
          6: "rich" }

然后,要访问数据,您可以执行以下操作:

x[1] // "kim"

x[4] // "gon"