-2

这是我有史以来的第一次问答,所以希望没问题。

作为一个快速上手的人,我发现这个话题的信息是零星的,而且通常过于复杂,很多人说根本做不到。所以这里很简单地分解了。

以这个场景为例,我们有许多表单组件(文本框、按钮等),它们都有许多属性,所有这些属性都有值……我们希望将它们存储在一个 javascript 数组中。

4

1 回答 1

0

这是我的修补程序。这段代码没有明确回答问题,因为没有明确提出问题,但我希望你觉得它有用

为了更好的衡量,这里还有一个 jsfiddle http://jsfiddle.net/cQ8Xc/

var $parent_arr = new Array();
var $child_arr = new Array();

//we can add the key => value pairs like so:
//(obviously they won't be done like this, more likely a loop for example)
//this works just fine $child_arr[$key] = $value;
$child_arr['Top'] = '12';
$child_arr['Left'] = '13';
$child_arr['Right'] = '14';
$child_arr['Bottom'] = '15';

//we can add the array to another array like so:
$parent_arr['component1'] = $child_arr;

//clear the array for reuse (note that it is obviously not nessecary to reuse the array)
$child_arr = [];

//refill it
//note that the child arrays don't have to be identical lengths or values
$child_arr['Height'] = '22';
$child_arr['Width'] = '23';
$child_arr['Colour'] = 'blue';

$parent_arr['component2'] = $child_arr;

//we can access the data like this:
alert($parent_arr['component1']['Top']);
alert($parent_arr['component2']['Colour']);

//these didn't work for me, you've likely seen them in other answers if you've been researching this topic
//alert(JSON.stringify($parent_arr['component1'], null, 4));
//alert(JSON.stringify($parent_arr['component1']));
//alert($parent_arr['component1'].join("\n"));

//the array can be looped over like so:
for(var component in $parent_arr) {
   for(var propertyName in $parent_arr[component]) {
      alert(component + '.' + propertyName + '=' + $parent_arr['component1'][propertyName]);
   }
}
于 2013-05-12T10:40:54.917 回答