简体   繁体   English

推送到多维数组Javascript

[英]push to multidimensional array Javascript

I have the following code: 我有以下代码:

    data_array =  {
                      full_name: 'fullname',
                      items: [],
                      address_full: 'address'
                  };

        first = {
            'data-opPrice'  : '1a',
            'data-stdPrice' : '1b',
            'state'         : '1c'
        };
        second = {
            'data-opPrice'  : '2a',
            'data-stdPrice' : '2b',
            'state'         : '2c'
        };          
        data_array.items.push(first);
        data_array.items.push(second);

    alert(data_array['items'][1].data-opPrice);

I would expect to get the alert "2a". 我希望收到警报“ 2a”。 But nothing happens. 但是什么也没发生。 Why? 为什么?

It's because of the - in data-opPrice . 这是因为-data-opPrice - is subtraction. -是减法。

alert(data_array['items'][1]['data-opPrice']);

http://jsfiddle.net/t9c7L/1/ http://jsfiddle.net/t9c7L/1/

您可能想要:

data_array.items[1]['data-opPrice'];

Try 尝试

alert(data_array['items'][1]['data-opPrice']);

because otherwise it's an operation ( data minus opPrice) 因为否则是一个操作(数据减去 opPrice)

用这个:

data_array.items[1]['data-opPrice']

use the naming conventions and don't use dash (minus) on properties name. 使用命名约定,并且不要在属性名称上使用破折号(减号)。

So follow these rules: http://javascript.crockford.com/code.html 因此,请遵循以下规则: http : //javascript.crockford.com/code.html

and then write a code like this: 然后编写如下代码:

data_array =  {
                  full_name: 'fullname',
                  items: [],
                  address_full: 'address'
              };

    first = {
        'dataOpPrice'  : '1a',
        'dataStdPrice' : '1b',
        'state'         : '1c'
    };
    second = {
        'dataOpPrice'  : '2a',
        'dataStdPrice' : '2b',
        'state'         : '2c'
    };          
    data_array.items.push(first);
    data_array.items.push(second);

alert(data_array.items[1].dataOpPrice);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM