使用javascript仅使用键值对生成和访问二维数组

时间:2017-01-23 12:33:13

标签: javascript jquery arrays

我想创建一个像:

这样的数组
var fruits[ ]=[ [1] ["Grapes","mango","orange"] , [2] ["banana"], [A] ["Avocado","Apple"] , [P] ["Pear","Papaya","pomegranate","plum"] ];

因此我想使用键值配对或类似的东西来访问上面的数组。

例如,如果我有一个带值的下拉列表:

<select>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="A">A</option>
  <option value="P">P</option>
</select>

根据我的选择,它应该使用for循环显示相应的值,就像我选择选项“A”然后使用for循环它应该显示对应于选项A的值。鳄梨苹果。

我怎样才能做到这一点?

3 个答案:

答案 0 :(得分:2)

您可以在+---+---------+---------+-----------+----------+---------+ | # | Monday | Tuesday | Wednesday | Thursday | Friday | +---+---------+---------+-----------+----------+---------+ | 1 | Biology | | | | | +---+---------+---------+-----------+----------+---------+ | 2 | | | Biology | | | +---+---------+---------+-----------+----------+---------+ | 3 | | | | | Biology | +---+---------+---------+-----------+----------+---------+ | 4 | | | | | | +---+---------+---------+-----------+----------+---------+ | 5 | | | | | | +---+---------+---------+-----------+----------+---------+ | 6 | | | | Physics | | +---+---------+---------+-----------+----------+---------+ | 7 | Math | | | | | +---+---------+---------+-----------+----------+---------+ | 8 | | Physics | | | | +---+---------+---------+-----------+----------+---------+ 上使用object而不是array并绑定change事件,然后使用select循环。

&#13;
&#13;
for
&#13;
var fruits = {
  1: ["Grapes", "mango", "orange"],
  2: ["banana"],
  A: ["Avocado", "Apple"],
  P: ["Pear", "Papaya", "pomegranate", "plum"]
}

$('select').change(function() {
  var val = $(this).val();
  if (fruits[val]) {
    for (var i = 0; i < fruits[val].length; i++) {
      console.log(fruits[val][i])
    }
  }
})
&#13;
&#13;
&#13;

答案 1 :(得分:0)

好像你想给元素数组赋予任意索引。在这种情况下, fruits 可以是普通对象,而不是数组。

var fruits = {
    1: ["Grapes", "mango", "orange"],   
    2: ["banana"],
    'A': ["avacado", "apple"],
    'P': ["Pear", "Papaya"]
}

您可以按如下方式访问任何类别;

fruit[1];    // ["Grapes", "mango", "orange"]
fruit['A'];  // ["avacado", "apple"]

答案 2 :(得分:0)

我如何用对象解决它:

<html>
<head></head>
<body>
    <div id="wrapper-select"></div>
<script>
var select,
    keyToUse = "A",
    fruits = {
        "1" : ["Grapes","mango","orange"],
        "2" : ["banana"],
        "A" : ["Avocado","Apple"],
        "P" : ["Pear","Papaya","pomegranate","plum"]
    },
    createOption = function createOption( text ) {
        var option = document.createElement('option');
        option.value = text;
        option.textContent = text;
        return option;
    };
// Select the fruits array we want to use.
// Then loop over it, appending a new option element to our select element.
select = fruits[keyToUse].reduce(function( select, fruitName ) {
    select.appendChild(createOption(fruitName));
    return select;
}, document.createElement('select') );
// Append the newly created select.
document.querySelector('#wrapper-select').appendChild(select);
</script>
</body>
</html>
相关问题