如何使用无效字符访问对象属性 [英] How to access object property with invalid characters

查看:21
本文介绍了如何使用无效字符访问对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 Angular 应用程序,该应用程序与已在使用的 Google Analytics API 交互.Google 返回的数据以ga:"为前缀,例如ga:newVisits".

I am writing an Angular app that interfaces with a Google Analytics API already in use. The data returned by Google is prefixed with "ga:" as in the example "ga:newVisits".

如果我使用表达式 {{total.ga:newVisits}},Angular 无法解析它.任何试图转义冒号以继续的尝试都会导致错误或完全转义我的表达式.

If I use the expression {{total.ga:newVisits}}, Angular cannot parse it. Any attempts at escaping the colon to continue has resulted in an error or escaping my expression altogether.

如何将 {{total.ga:newVisits}} 传递给 Angular 以便表达式正常工作?

<!doctype html>
  <html ng-app="AnalyticsApp">
    <head>
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.min.js"></script>
      <script src="angular-controller.js"></script>
    </head>
    <body ng-controller="AnalyticsCtrl">
      <ul>
        <li ng-repeat="total in result">
          {{total.ga:newVisits}}
        </li>
      </ul>
    </body>
  </html>

推荐答案

在 JavaScript 中,可以通过点表示法或括号表示法访问对象属性.点符号通常更简洁,但也有限制.正如您所注意到的,您的属性包含无效字符,因此无法通过点表示法访问.然后,解决方案是使用如下方括号表示法访问属性: total['ga:newVisits'] 这样您的完整代码将是 {{total['ga:newVisits']}}.现场演示(点击).

In JavaScript, object properties can be accessed by dot notation or bracket notation. Dot notation is often cleaner, but has restrictions. As you have noticed, your property contains an invalid character and therefore can't be accessed via dot notation. The solution, then, is to access the property using bracket notation like this: total['ga:newVisits'] so that your complete code will be {{total['ga:newVisits']}}. Live demo here (click).

括号表示法的另一个优点是它允许您使用变量名作为属性:

Another nice feature about bracket notation is that it allows you to use a variable name as a property:

var myObj {
  bar: '123'
};
var foo = 'bar';

console.log(myObj[foo]); //logs '123'

这篇关于如何使用无效字符访问对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆