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

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

问题描述

使用此脚本制作所有继承等样式的样式对象。

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 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"]

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

All arrays in js 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 [会给你一个未定义的错误
而obj [method]不会

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

你必须如果你使用的是js变量中不允许的字符,请使用这种表示法。

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

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

This regex pretty much sums it up

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

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

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