代码之家  ›  专栏  ›  技术社区  ›  0plus1

javascript:具有键值可选的多维数组?

  •  2
  • 0plus1  · 技术社区  · 15 年前

    Since I'm more versed in php thank in js I'll try to explain what I need from a php perspective. I need to pass to a javascript function an array:

    array('fieldname' => 'value', 'fieldname2' => 'value2' ...);
    

    函数可以做到这一点

    foreach(array as k => v) {
      <input name='fieldname' value='value'/>
      <input name='fieldname2' value='value2'/>
      ...
    }
    

    I don't know how to do this, I understand that js don't have multidimensional array, so I wonder what is the correct way to do this in javascript?

    非常感谢你

    4 回复  |  直到 15 年前
        1
  •  5
  •   John Kugelman Michael Hodel    15 年前
    <script type="text/javascript">
    // <![CDATA[
    
      // Create an associative array.
      var array = {'fieldname': 'value', 'fieldname2': 'value2'};
    
      for (var key in array) {
          // Create an input element and set its name and value.
          var input = document.createElement("input");
    
          input.name  = key;
          input.value = array[key];
    
          // There's no simple "insert an element right here"; you have to pick
          // where in the document to add the input box.
          document.body.appendChild(input);
      }
    
    // ]]>
    </script>
    
        2
  •  3
  •   g.d.d.c    15 年前

    在javascript中没有关联数组。有些对象提供键值对,但它们确实不应该与关联数组混淆。你可以这样做:

    var myObject = {
      key1: 'value1',
      key2: 'value2'
    };
    
    for (var i in myOjbect) {
      var thisVal = myObject[i];
    }
    

    这将允许您迭代所创建对象的属性。同样,虽然这类似于您所请求的,但它与PHP中的关联数组并不完全相同。

        3
  •  0
  •   kasperjj    15 年前

    var fields={'fieldname' : 'value', 'fieldname2' : 'value2'};
    for(var key in fields){
        var elm=document.createElement('input');
        elm.name=key;
        elm.value=fields[key];
        document.body.appendChild(elm);
    }
    
        4
  •  0
  •   codez    15 年前

    JS中的多人阵列:

    a={a:{a:1,b:2},b:{a:1,b:2}};
    a.a.a=5;
    a['a']['a']=7;