访问动态创建的对象.. js

时间:2017-01-04 13:06:02

标签: javascript loops object

我无法访问已在循环内创建的对象。

// global var $subtypes //

...
... code ...
...

$subtypes = {};

for ( var $cols = 0; $cols < $subtypecols.length; $cols++ ) // Here i can got from 1 to 20 
{
    var columnName = 'column' + $cols; // column0, column1, column2 ... column20
    $subtypes.columnName = {  };  // creating empty object

    for ( var $rows = 0; $rows < $subtypeTableRows.length; $rows++ ) // from 1 to 10.
    {
        var rowNumber = 'row' + $rows; // row1, row2, row3 ... row7
        $subtypes.columnName.rowNumber = { 'count' : -1, 'price' : -1 };
    };
};
//console.log ( 'l ' +  $subtypes['column3']['row5'] ); //undefined is not an object (evaluating '$subtypes['column3']['row5']')
//console.log ( 'l ' +  $subtypes['column3']['row5'].count ); //undefined is not an object (evaluating '$subtypes['column3']['row5']')
//console.log ( 'l ' +  $subtypes[column3][row5].count ); //ReferenceError: Can't find variable: column3
//console.log ( 'l ' +  $subtypes[column3][row5] ); //ReferenceError: Can't find variable: column3
//console.log ( 'l ' +  $subtypes.column3.row5 ); //expected 'object', got: undefined is not an object (evaluating '$subtypes.column4.row2')

我做错了什么?

UPD 1:该代码不起作用..

for (var o = 0; o < 5; o++)
{
    var $prevNum = 'prev' + o;
    var $prevTxt = $nodelist[o].textContent

    $itemConfig = {     $itemWithPreviews : { $prevNum : $prevTxt }     }; 
    // i got string name '$prevNum' : and value from valiable $prevTxt.

    $itemConfig = {     $itemWithPreviews : { [$prevNum] : $prevTxt }   }; 
    // JS script can't start
};

UPD 2:

var $root = {};
var $root[0] = {}; // data
var $root[1] = {}; // another data
var $root[2] = {}; // here will be stored buttons and rows.. 

for ( var $buttons = 0; $buttons < 10; $buttons++ ) // 10 buttons
{
    var buttonName = 'button' + $buttons; // button0, button1, button2 ... buttom9

    var objButton = { };
    objButton[buttonName] = { }; 
    $root[2].push( objButton ); //here all's ok: { "button0":{} }, { "button1":{} } ... 


    for ( var $row = 0; $row < 5; $row++ )
    {
        var rowNumber = 'row' + $row; // row0, row2 ... row4


        var objRow = { };
        objRow[rowNumber] = { }; 

        $root[2][buttonName].push ( objRow ); 
        // Expect.: { "button0": { "row0": { }, "row1": { }, "row2": { }, ...  } }, { "button1": { "row0": { }, "row1": { }, "row2": { }, ...  } } ... 
        // Got: ERROR: TypeError: undefined is not an object (evaluating '$root[2][buttonName].push')

        //same situation...
        $root[2][$buttons].push ( objRow );
        // Got: ERROR: TypeError: undefined is not a function (evaluating '$root[2][$buttons].push ( objRow )')

    };
};

2 个答案:

答案 0 :(得分:2)

你做了:

$subtypes.columnName = {  };
$subtypes.columnName.rowNumber = { 'count' : -1, 'price' : -1 };

创建对象:

$subtypes["columnName"]["rowNumber"];

如果您想创建$subtypes['column3']['row5'],则需要执行以下操作:

$subtypes[columnName] = {  };
$subtypes[columnName][rowNumber] = { 'count' : -1, 'price' : -1 };

请注意,点符号a.b.c相当于a['b']['c']。因此,您的console.log()也可以写成:

console.log ( 'l ' +  $subtypes.column3.row5 );

更新

关于你的后续问题,当你这样做时

$itemConfig = {$itemWithPreviews : { $prevNum : $prevTxt }}; 

您正在创建以下对象:

$itemConfig["$itemWithPreviews"]["$prevNum"] = $prevTxt;

属性名称是不是变量。它们总是被解释为文字字符串。因此,$prevNum "$prevNum"不是"prev0"等。另一方面,属性值为ARE变量,因此$prevTxt具有相同的值。

ES6(也称为ES2015)引入了一种新语法called computed property names,可让您按照自己的意愿行事。执行此操作的语法使用熟悉的方括号:

$itemConfig = {[$itemWithPreviews] : {[$prevNum] : $prevTxt }};

但是,截至2017年1月,只有Chrome,Firefox和Node.js支持此语法。这在其他浏览器中不起作用,所以你必须以oldschool方式进行:

$itemConfig = {};
$itemConfig[$itemWithPreviews] = {};
$itemConfig[$itemWithPreviews][$prevNum] = $prevTxt;

如果要在循环中执行此操作,可以有条件地初始化属性:

$itemConfig = {};

for (var o = 0; o < 5; o++) {
    var $prevNum = 'prev' + o;
    var $prevTxt = $nodelist[o].textContent;

    if ($itemConfig[$itemWithPreviews] === undefined) {
        $itemConfig[$itemWithPreviews] = {};
    }

    if ($itemConfig[$itemWithPreviews][$prevNum] === undefined) {
        $itemConfig[$itemWithPreviews][$prevNum] = {};
    }

    $itemConfig[$itemWithPreviews][$prevNum] = $prevTxt;
}

答案 1 :(得分:0)

$subtypes.columnName将创建文字columnName属性。使用[]来使用动态命名:

$subtypes = {};

for (var $cols = 0; $cols < 5; $cols++) {
  var columnName = 'column' + $cols;
  $subtypes[columnName] = {};

  for (var $rows = 0; $rows < 6; $rows++) {
    $subtypes[columnName]['row' + $rows] = {'count': -1, 'price': -1};
  };
};

console.log($subtypes);