简体   繁体   English

出色的javascript示例和属性中字符串的用法

[英]Eloquent javascript example and usage of strings in properties

I am currently going through Eloquent Javascript and this is a question about properties and usage of strings in those properties. 我目前正在阅读Eloquent Javascript ,这是一个有关属性以及这些属性中字符串使用情况的问题。

I am looking at two objects in chapter 4: 我正在看第4章中的两个对象:

http://eloquentjavascript.net/code/jacques_journal.js http://eloquentjavascript.net/code/jacques_journal.js

and

var journal = [
  {events: ["work", "touched tree", "pizza",
            "running", "television"],
   squirrel: false},
  {events: ["work", "ice cream", "cauliflower",
            "lasagna", "touched tree", "brushed teeth"],
   squirrel: false},
  {events: ["weekend", "cycling", "break",
            "peanuts", "beer"],
   squirrel: true},
  /* and so on... */
];

question: Do the property names need to be strings like in the Jacques Journal object? 问题:属性名称是否需要像Jacques Journal对象中的字符串? OR can they can just be listed as events and squirrel in the above object? 还是可以将它们仅列为上述对象中的事件和松鼠?

In either case, will this code still work: 无论哪种情况,此代码仍然有效:

function tableFor(event, journal) {
return journal.events.indexOf(event)
}

tableFor("pizza", JOURNAL)    (notice that the JOURNAL object is found within the link provided)

What does everyone use to test Javascript code with lots of indentation? 每个人都使用什么来测试带有大量缩进的Javascript代码? I tried using the Dev tools in chrome but it's annoying to have to manually type in indentation with the space bar. 我尝试在chrome中使用开发工具,但必须手动使用空​​格键输入缩进很烦人。 Can you test javascript code in Sublime Text? 您可以在Sublime Text中测试javascript代码吗?

var foo = { "bar": 123 };
var foo = { bar: 123 };

The above two lines of JavaScript are exactly equivalent. 以上两行JavaScript完全相同。 In either case you can access the "bar" property in two different ways: 无论哪种情况,您都可以通过两种不同的方式访问"bar"属性:

console.log( foo.bar );     # => 123
console.log( foo["bar"] );  # => 123

You only need to use the quotation mark syntax ( { "bar": 123 } ) when the key isn't a valid JavaScript identifier. 当密钥不是有效的JavaScript标识符时,只需使用引号语法( { "bar": 123 } )。 To quote MDN : 引用MDN

A JavaScript identifier must start with a letter, underscore (_), or dollar sign ($); JavaScript标识符必须以字母,下划线(_)或美元符号($)开头; subsequent characters can also be digits (0-9). 后续字符也可以是数字(0-9)。 Because JavaScript is case sensitive, letters include the characters "A" through "Z" (uppercase) and the characters "a" through "z" (lowercase). 因为JavaScript区分大小写,所以字母包括字符“ A”至“ Z”(大写)和字符“ a”至“ z”(小写)。

Starting with JavaScript 1.5, you can use ISO 8859-1 or Unicode letters such as å and ü in identifiers. 从JavaScript 1.5开始,您可以在标识符中使用ISO 8859-1或Unicode字母,例如å和ü。 You can also use the \\uXXXX Unicode escape sequences as characters in identifiers. 您也可以使用\\ uXXXX Unicode转义序列作为标识符中的字符。

For example, this is valid: 例如,这是有效的:

var obj = { "": 1,
            "!": 2,
            "foo bar": 3,
            "99bottles": 4 }

But without the quotation marks, any of those would throw an error. 但是,如果没有引号,则其中任何一个都将引发错误。

There's one other time when quotation marks are necessary, and that's when you want to use a key that's a reserved word in JavaScript, like return or else or class . 还有另外一次需要使用引号的情况,那就是您要使用JavaScript中保留字的键,例如returnelseclass Sometimes you can do it just fine: 有时您可以做得很好:

var obj = { else: 123 }
console.log( obj.else ) # => 123

...but this depends on the JavaScript parser being able to tell that you're using it as a property name and not as a keyword. ...但是,这取决于JavaScript解析器能否告诉您将其用作属性名而不是关键字。 If, for example, you open up your JavaScript console right now and type: 例如,如果您现在打开JavaScript控制台并键入:

{ else: 123 }

...you'll get a SyntaxError. ...您将收到一个SyntaxError。 So, when it comes to words that have special meaning in JavaScript (there's a full list here ), it's best to use quotation marks: 因此,对于在JavaScript中具有特殊含义的单词(此处有完整列表 ),最好使用引号:

var obj = { "else": 123 }

On the other side of the coin—which is to say, getting things out of the object you've created—the story is much the same. 在硬币的另一面(也就是说,从您创建的对象中取出东西),故事几乎是相同的。 Suppose we have this object: 假设我们有这个对象:

var obj = { foo: 1,  // note that we can mix quoted and non-quoted if we want
            "": 2,
            "99bottles": 3,
            "else": 4,
            "foo bar": 5,
            $gt: 6 }

For keys that are valid identifiers, we can use regular "dot notation" to access the properties, but for the others we have to use "bracket notation": 对于有效标识符的键,我们可以使用常规的“点符号”来访问属性,但是对于其他键,我们必须使用“括号符号”:

obj.foo          # => 1
obj[""]          # => 2
obj.99bottles    # => SyntaxError: Unexpected token ILLEGAL
obj["99bottles"] # => 3
obj.else         # => 4
obj["foo bar"]   # => 5
obj.$gt          # => 6

Finally, it's worth noting that JSON is a subset of JavaScript. 最后,值得注意的是JSON是JavaScript的子集 This is valid JavaScript, but it's not a valid JSON object: 这是有效的JavaScript,但不是有效的JSON对象:

{ foo: "bar" }

Quotation marks are required around JSON property names. JSON属性名称必须带引号。 The below is valid JSON: 以下是有效的JSON:

{ "foo": "bar" }

First of all your your last snippet will throw following error: 首先,您的最后一个片段将引发以下错误:

Uncaught TypeError: Cannot read property 'indexOf' of undefined

This is right because there is no element with value "pizza" in your journal array. 这是正确的,因为您的journal数组中没有值"pizza"元素。 You have just some json objects in your array. 您的数组中只有一些json对象。 So you have to iterate through all objects to find out the value of property squirrel . 因此,您必须遍历所有对象以找出squirrel属性的值。

Something like this will work: 这样的事情会起作用:

function tableFor(event, journal) {
    for(var i=0;i<journal.length;i++){
      if(journal[i].events.indexOf(event) > 0) return journal[i].squirrel;
    }
    return false;
}

Keep in mind that everything in javascript is an object, so you can "abuse" an Array object by setting arbitrary properties on it. 请记住,javascript中的所有内容都是一个对象,因此您可以通过在其上设置任意属性来“滥用” Array对象。 Use Arrays for numerically indexed data and objects for non-numeric keys. 将数组用于数字索引数据,将对象用于非数字键。

More information in this stackoverflow post 此stackoverflow 帖子中的更多信息

There are many ways to test your javascript... You can do it online ( jsfiddle for example) or in your console in browser. 有很多方法可以测试您的JavaScript ...您可以在线(例如jsfiddle )或在浏览器的控制台中进行测试。

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

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