如何引用带有连字符的 JavaScript 对象属性? [英] How do I reference a JavaScript object property with a hyphen in it?

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

问题描述

我正在使用 这个脚本 将所有继承的等样式创建一个样式对象.

I am using this script to make a style object of all the inherited, etc. styles.

var style = css($(this));
alert (style.width);
alert (style.text-align);

使用以下内容,第一个警报可以正常工作,但第二个警报不会……它将 - 解释为我假设的减号.调试器说未捕获的引用错误".但是,我不能在它周围加上引号,因为它不是字符串.那么我该如何使用这个对象属性呢?

With the following, the first alert will work fine, but the second one doesn't... it's interpreting the - as a minus I assume. The debugger says 'uncaught reference error'. I can't put quotes around it, though, because it isn't a string. So how do I use this object property?

推荐答案

看评论.您将看到,对于 CSS 属性,关键符号与许多属性不兼容.因此,使用驼峰式键符号是当前的方式:

Look at the comments. You will see that for CSS properties, the key notation is not compatible with a number of properties. Using the camel case key notation therefore is the current way:

obj.style-attr // would become

obj["styleAttr"]


使用键符号而不是点


Use key notation rather than dot

style["text-align"]

JavaScript 中的所有数组都是对象,所有对象都只是关联数组.这意味着您可以像引用数组中的键一样引用对象中的位置.

All arrays in JavaScript are objects and all objects are just associative arrays. This means you can refer to a place in an object just as you would refer to a key in an array.

arr[0]

或对象

obj["method"] == obj.method

以这种方式访问​​属性时要记住的几件事:

A couple things to remember when accessing properties this way:

  1. 对它们进行评估,因此除非您使用计数器或使用动态方法名称执行某些操作,否则请使用字符串.

  1. they are evaluated so use strings unless you are doing something with a counter or using dynamic method names.

这意味着 obj[method] 会给你一个未定义的错误而 obj[method"] 不会

This means obj[method] would give you an undefined error while obj["method"] would not

如果您使用 JavaScript 变量中不允许使用的字符,则必须使用此表示法.

You must use this notation if you are using characters that are not allowed in JavaScript variables.

这个正则表达式几乎总结了它:

This regex pretty much sums it up:

[a-zA-Z_$][0-9a-zA-Z_$]*

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

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