简体   繁体   English

对象中的对象的JavaScript点表示法

[英]JavaScript Dot Notation with Objects in Objects

I am playing around with JS at the moment, coming from Java. 我现在正在玩JS,来自Java。 I did some Tutorials and need some help with the dot and bracket notation in JS. 我做了一些教程,需要帮助JS中的点和括号表示法。

I made something, I consider an "Object" in JS. 我做了一些东西,我认为JS中的“对象”。 Its called "friends". 它被称为“朋友”。 Within this object, there is another object "bill". 在这个对象中,还有另一个对象“bill”。

var friends = {};
 friends.bill = {
  firstName: "Bill",
  lastName: "Gates",
  number: "(206) 555-5555",
  address: ['One Microsoft Way','Redmond','WA','98052']
 };

 var search = function(name) {
 for(var prop in friends) {
  if(friends[prop].firstName === name) {
   return friends[prop];
  }
 }
};
search("Bill");

This is clearly working as intended. 这显然是按预期工作的。 I used bracket notation in the search-function. 我在搜索功能中使用括号表示法。 BUT it isnt clear to me why this version wouldnt work the same way: 但是我不清楚为什么这个版本不会以同样的方式工作:

 var search = function(name) {
 for(var prop in friends) {
  if(friends.prop.firstName === name) {
   return friends.prop;
  }
 }

In my understanding, bracket and dot notation are used for the same things. 根据我的理解,括号和点符号用于相同的事情。 I did a search on stackoverflow and I think this question goes the same way, but I think I do not fully understand whats the problem with all the quotation marks. 我在stackoverflow上搜索了一下,我觉得这个问题也是这样,但我想我并不完全理解所有引号的问题。

When you use the bracket notation, you put the name of the property you want to access between the brackets, the name is a string. 使用括号表示法时,在括号之间放置要访问的属性的名称,名称是字符串。

When you use the dot notation, you type the property name and not the string containing the property name after the dot. 使用点表示法时,键入属性名称,而不是包含点后属性名称的字符串。

Your line: 你的路线:

friends.prop

Is interpreted like this by JavaScript: JavaScript解释如下:

Look for a property named prop on the object friends , and there is no such property so you get problems. 在对象friends上查找名为prop的属性,并且没有这样的属性,因此您会遇到问题。

You can't use a variable with dot notation. 您不能使用带点符号的变量。 The variable won't be evaluated. 不会评估变量。 JavaScript will try to access the property prop from your object which doesn't exist therefore the second solution is not working. JavaScript将尝试从您的对象访问属性prop ,这是不存在的,因此第二个解决方案无法正常工作。

friends.firstName相当于friends ['firstName']

As mentioned friends.prop.firstName doesn't evaluate the prop as variable, but as property of the friends object. 如上所述, friends.prop.firstName不会将prop评估为变量,而是作为friends对象的属性。

You could evaluate the string into an object, if you, for some reason, would like to use this type of a notation. 如果由于某种原因,您希望使用这种类型的表示法,则可以将字符串计算为对象。

var search = function(name) {
  for(var prop in friends) {
    if(eval("friends."+prop+".firstName) === name) {
     return eval("friends."+prop);
    }
  }
};

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

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