Javascript:具有键值替代的多维数组?

0pl*_*us1 2 javascript arrays

因为我对php更精通php感谢js我会尝试从php的角度解释我需要什么.我需要传递一个javascript函数数组:

array('fieldname' => 'value', 'fieldname2' => 'value2' ...);
Run Code Online (Sandbox Code Playgroud)

该功能可以做到这一点

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

我不知道怎么做,我明白js没有多维数组,所以我想知道在javascript中这样做的正确方法是什么?

ps我明白有一个库可以为js提供php函数,但我想学习在纯js中执行此操作的最佳实践.

非常感谢你

Joh*_*ica 5

<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>
Run Code Online (Sandbox Code Playgroud)