开发者

Javascript: multimensional arrays with key value alternative?

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' ...);

Thne the function would do this

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 wonde开发者_开发百科r what is the correct way to do this in javascript?

p.s. I understand that there is a library that make available the php function to js, but I want to learn what is the best practice to do this in pure js.

Thank you very much


<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>


In Javascript there are no associative arrays. There are Objects which provide key-value pairings, but they really should not be confused with an associative array. You can do things like this:

var myObject = {
  key1: 'value1',
  key2: 'value2'
};

for (var i in myOjbect) {
  var thisVal = myObject[i];
}

That will allow you to iterate over the properties of the object you've created. Again, while this is similar to what you've requested, it is not exactly the same as an associative array in PHP.


I might be missing something since I'm not quite sure what you mean when you say multidimensional array... what you are showing in your code is typically called an associative array.

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);
}


multidimensianla array in js:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜