[英]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. 问题是在任何范围内都没有将coffee定义为变量,您可以使用obj ['coffee']的表示法将coffee作为字符串传递,以使其工作。 Or you can call it as slot1.coffee in order for you to get to it. 或者,您也可以将其称为slot1.coffee,以便您使用它。
The upper version does not work because of these two lines 由于这两行,较高的版本不起作用
var item = obj + '.' + prop;
& findItem( slot1, coffee );
& findItem( slot1, coffee );
When retrieving an object ab
or a['b']
is enough where a is the object and b is key 检索对象ab
或a['b']
就足够了,其中a是对象而b是键
Doing a +'.'+b will result in concatenation ,instead of retrieving the value. 进行+'。'+ b将导致串联,而不是检索值。
In function pass coffee
as string otherwise it will pass as undefined value because it will presume coffee is declared somewhere which is not 在函数中,将coffee
作为字符串传递,否则它将作为未定义的值传递,因为它将假定在不是
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' );
尝试使用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. 当您在变量中具有属性名称时,请使用诸如数组myObject[property]
类的对象,其中property是一个变量,其中包含要获取的对象的属性名称。
Also, coffee
is not to be used as variable but a string "coffee"
or 'coffee'
另外, coffee
不用作变量,而应用作字符串"coffee"
或'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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.