需要说明:联系人列表中包含对象的组织(Javascript,Codecademy) [英] Need Explanation: Organization with Objects in a Contact List (Javascript, Codecademy)
问题描述
在联系人列表项目中,我一直无法理解两个javascript函数=http://bit.ly/Zroroe =nofollow> codecademy 。
I've been having some trouble making sense of two javascript functions in this contact list project on codecademy.
具体来说,我对obj或prop等条件感到困惑。
如果有人可以详细解释这些功能是如何工作的,我将非常感激。
Specifically, I got confused with conditions like, "obj" or "prop". I would really appreciate it if someone can explain in detail how these functions work.
这是代码&谢谢你:
Here is the code & thank you:
var friends = {};
friends.bill = {
firstName: "Bill",
lastName: "Gates",
number: "(206) 555-5555",
address: ['One Microsoft Way','Redmond','WA','98052']
};
friends.steve = {
firstName: "Steve",
lastName: "Jobs",
number: "(408) 555-5555",
address: ['1 Infinite Loop','Cupertino','CA','95014']
};
var list = function(obj) {
for(var prop in obj) {
console.log(prop);
}
};
var search = function(name) {
for(var prop in friends) {
if(friends[prop].firstName === name) {
console.log(friends[prop]);
return friends[prop];
}
}
};
list(friends);
search("Steve");
推荐答案
obj
只是您正在创建的 list
函数的参数名称。它没有特别的意义。您可以将其称为 foo
或 object
,或其他任何对您有意义的事情。传递给list的函数调用的参数的值(上面,即 friends
)存储在函数范围内的参数中。也就是说, obj
在列表代码内操作时基本上变为
。朋友
obj
is just the name of the parameter of the list
function that you are creating. It has no special meaning. You could call it foo
or object
, or anything else that makes sense to you. The value of the argument you pass to the function call of list (above, namely friends
) is stored in the parameter in the scope of the function. That is to say, obj
essentially becomes friends
while operating inside the code of list
.
prop
类似:它只是作为JavaScript的一部分创建的变量< a href =https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/for...in =nofollow> for ... in
语法。在中的循环对象的属性名称,该对象是
构造中的参数,并逐个存储它们在
prop
中。再一次,你可以随意调用它:
prop
is similar: it's just a variable that is created as part of JavaScript's for...in
syntax. for in
loops over the property names of the object that is the argument to the in
construct and stores them one by one in prop
. Again, you could call this whatever you wanted:
var list = function (foo) {
for (var bar in foo) {
但是,我确信你已经学会了,给它是有意义的变量名有一些含义,因此 obj
是object的缩写,因为 list
函数可以对任何常规对象进行操作,并且 prop
是property的缩写。
However, as I'm sure you've learned, it makes sense to give variable names some meaning, so obj
is short for "object" as the list
function operates on any general object, and prop
is short for "property."
请记住表示...在
中遍历属性名称。要访问对应的值,您应该使用:
Keep in mind that for...in
loops over property names. To access the correspoding value, you should use:
if (obj.hasOwnProperty(prop)) {
//access via obj[prop];
}
搜索
功能实际上这样做,但没有推荐的 hasOwnProperty
检查。
The search
function actually does this, but without the recommended hasOwnProperty
check.
这篇关于需要说明:联系人列表中包含对象的组织(Javascript,Codecademy)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!