【问题标题】:javascript can't get object property valuejavascript无法获取对象属性值
【发布时间】:2016-11-08 09:21:54
【问题描述】:

我有如下的 javascript 对象:

var row = {
              'fileAttribute' : {
                  '.\K\ar- #%i\.n/a': true,
                  'size': '2040',
                  'type' : 'pdf'
                  }
    };

但是当我尝试获取 row.fileAttribute['.\K\ar- #%i.n/a'] 的值时,我得到的是 undefined 而不是 true。

我知道这是因为我的属性名称包含特殊字符。 row.fileAttribute.hasOwnProperty('.\K\ar- #%i.n/a') 返回 false。

我尝试通过 _.values(row.fileAttribute['.\K\ar- #%i.n/a']) 提取此属性值,但是我得到了空数组。

我的控制台:

这里是这个问题的一个例子:

http://jsfiddle.net/fvu2pqzz/8/

感谢您的帮助,谢谢!

【问题讨论】:

  • 您链接的代码与row.fileAttributes['.\K\ar- #%i.n/a'])有很大不同
  • 绝对是错字。应该是fileAttribute 没有s,不应该吗?
  • 似乎工作:jsfiddle.net/fvu2pqzz/8
  • 您无法通过点表示法访问该属性,因为它包含无效字符。括号符号将起作用
  • 截图说你有一个名为.K\ar- #%i.n/a的键,表示\已经被转义了,所以需要使用item.fileAttributes['.K\\ar- #%i.n/a']来获取。

标签: javascript object properties attributes


【解决方案1】:

你需要使用bracket notation

console.info(row.entity.fileAttribute['.Kar- #%i.n/a']);

var row = {
            'entity' : {
                'fileAttribute' : {
                    '.\K\ar- #%i\.n/a': true,
                    'size': '20',
                    'qty' : '50'
                },
                'part2' : {
                    'name': 'Part 2',
                    'size': '15',
                    'qty' : '60'
                }
            }
        };
        
console.info(row.entity.fileAttribute['.Kar- #%i.n/a']);

【讨论】:

  • @AminPourhadi 我刚刚用你的对象测试了它,它返回了 true
  • @AminPourhadi 你一定在做别的事
  • 感谢@shivgre,但这段代码在小提琴中正常工作,而在我的不起作用:(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-29
  • 1970-01-01
  • 2016-06-30
  • 1970-01-01
  • 1970-01-01
  • 2016-09-27
相关资源
最近更新 更多