2017-04-22 90 views
0

我在做JavaScript問題,這裏有一個問題,我得到了1/2答案的權利。我不知道如何在給定鍵沒有屬性的情況下返回undefined。這是問題和我的代碼。如何在給定鍵沒有屬性的情況下返回undefined?

「給定一個對象的關鍵,‘的getProperty’在給定的鍵返回屬性的值

注: *如果在給定的鍵的屬性,它應該返回不確定的。」

function getProperty(obj, key) { 
    for (var x in obj) { 
    return obj[x]; 
    } 
} 
+2

循環是,你從最初的迭代返回無用的付出。 –

+2

'function getProperty(obj,key){return obj [key]; }'將返回值或'undefined'。 –

回答

4

可以使用hasOwnProperty功能,例如:

function getProperty(obj, key){ 
 
    return obj.hasOwnProperty(key) ?obj[key] : undefined; 
 
} 
 

 
// Examples 
 
console.log(getProperty({a: 1, b: 2}, "a")); 
 
console.log(getProperty({a: 1, b: 2}, "c"));

更新你可以更簡單的方式

function getProperty(obj, key){ 
 
     return obj[key]; 
 
} 
 

 
// Examples 
 
console.log(getProperty({a: 1, b: 2}, "a")); 
 
console.log(getProperty({a: 1, b: 2}, "c"));

+0

兩者都可以。雖然我更喜歡第一個,因爲它不會看到原型鏈。 –

+0

我認爲只有第二個是有效的。它不說只返回自己的財產,它說財產。 –

1

你不需要這個功能。直接調用它:

obj[key]; // Return value or 'undefined' if not found. 

此外,你的功能是無用的。它只返回OBJ

發現如果你真的想要一個函數的第一個值,只是這會做

function getProperty(obj, key) { 
    return obj[key]; 
} 
相關問題