简体   繁体   中英

function variable undefined

Why does the top version not work and the lower function works? Learning about how to create and use objects and this baffles me. I assume it has to do with the fact I am using an object in the top part?

 var slot1 = { coffee: '1', tea: '2', espresso: '3' } function findItem( obj, prop ){ var item = obj + '.' + prop; console.log(item); } findItem( slot1, coffee ); function addNumbs(num1,num2){ var answer = num1+num2; console.log(answer); } addNumbs(4,3); 

Right when I think I am getting the hang of it I get completely slapped in the face!

The problem is that coffee is not defined in any scope as a variable, you can use the notation of obj['coffee'] passing coffee as a string in order for this to work. Or you can call it as slot1.coffee in order for you to get to it.

The upper version does not work because of these two lines

var item = obj + '.' + prop; & findItem( slot1, coffee );

When retrieving an object ab or a['b'] is enough where a is the object and b is key

Doing a +'.'+b will result in concatenation ,instead of retrieving the value.

In function pass coffee as string otherwise it will pass as undefined value because it will presume coffee is declared somewhere which is not

Make this change

var slot1 = {
  coffee: '1',
  tea: '2',
  espresso: '3'
}

function findItem( obj, prop ){
  var item = obj[prop];
  document.write('<pre>'+item+'</pre>')
}
findItem( slot1,'coffee' );

DEMO

尝试使用slot1.coffee代替咖啡

findItem( slot1, slot1.coffee );

When you have property name in a variable use object like an array myObject[property] where property is a variable which contains a name of property of object you wanna get the value of.

Also, coffee is not to be used as variable but a string "coffee" or 'coffee'

 var slot1 = { coffee: '1', tea: '2', espresso: '3' } function findItem( obj, prop ){ var item = obj[prop]; // You need to access object property as if object was an array when you have property name in variable. console.log(item); } findItem( slot1, 'coffee' ); // You need coffee as a string here, variable coffee was never defined function addNumbs(num1,num2){ var answer = num1+num2; console.log(answer); } addNumbs(4,3); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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