[英]function variable undefined
為什么最高版本不起作用而較低功能起作用? 了解如何創建和使用對象,這讓我感到困惑。 我認為這與我在頂部使用對象有關嗎?
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);
沒錯,當我認為自己掌握了這些要訣時,我就完全被打了巴掌!
問題是在任何范圍內都沒有將coffee定義為變量,您可以使用obj ['coffee']的表示法將coffee作為字符串傳遞,以使其工作。 或者,您也可以將其稱為slot1.coffee,以便您使用它。
由於這兩行,較高的版本不起作用
var item = obj + '.' + prop;
& findItem( slot1, coffee );
檢索對象ab
或a['b']
就足夠了,其中a是對象而b是鍵
進行+'。'+ b將導致串聯,而不是檢索值。
在函數中,將coffee
作為字符串傳遞,否則它將作為未定義的值傳遞,因為它將假定在不是
進行更改
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 );
當您在變量中具有屬性名稱時,請使用諸如數組myObject[property]
類的對象,其中property是一個變量,其中包含要獲取的對象的屬性名稱。
另外, 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.