假设我有一个函数,该函数接受语言作为参数,并根据此参数返回在对象上定义的一种语言:
function greet(language) {
var greeting = {english: 'Welcome',
czech: 'Vitejte',
danish: 'Velkomst',
dutch: 'Welkom',
estonian: 'Tere tulemast',
finnish: 'Tervetuloa',
flemish: 'Welgekomen',
french: 'Bienvenue',
german: 'Willkommen',
irish: 'Failte',
italian: 'Benvenuto',
latvian: 'Gaidits',
lithuanian: 'Laukiamas',
polish: 'Witamy',
spanish: 'Bienvenido',
swedish: 'Valkommen',
welsh: 'Croeso'}
return greeting.language
}
执行此操作时,我不确定,这意味着没有为语言分配任何值,那么如何使语言等于键之一?
答案 0 :(得分:3)
使用greeting.language
等效于greeting['language']
,但是'language'
不是greeting
的属性。
相反,您想将language
视为变量,所以请使用greeting[language]
。因此,如果输入为'polish'
,则您的函数将返回greeting['polish']
。
答案 1 :(得分:0)
由于拥有动态对象,因此应该执行此操作,因为它是对象的未知属性,对于动态属性,可以使用方括号=>
function greet(language) {
var greeting = {english: 'Welcome',
czech: 'Vitejte',
danish: 'Velkomst',
dutch: 'Welkom',
estonian: 'Tere tulemast',
finnish: 'Tervetuloa',
flemish: 'Welgekomen',
french: 'Bienvenue',
german: 'Willkommen',
irish: 'Failte',
italian: 'Benvenuto',
latvian: 'Gaidits',
lithuanian: 'Laukiamas',
polish: 'Witamy',
spanish: 'Bienvenido',
swedish: 'Valkommen',
welsh: 'Croeso'}
return greeting[language]
}
console.log(greet("danish"))