2016-06-16 5 views
0

JavaScriptのデバッグに関する問題JavaScriptで国リストを照会する

私は国名をそれぞれの2桁のISO国コードに変換する必要があります。この問題については、初期の国の変数を名前として、次のオブジェクトを作成しました。

var country = 'Andorra' // the input country (I had to throw in the apostrophes because of country names such as "Congo Republic of" that would recognise of as a keyword if not kept in apostrophes.) 
var country_code = countrylist[country] 
var countrylist = { 
'Andorra': 'AD', 
'United Arab Emirates': 'AE', 
'Afghanistan': 'AF', 
'Antigua and Barbuda': 'AG', 
'Anguilla': 'AI', 
'Albania': 'AL', 
'Armenia': 'AM', 
'Angola': 'AO', 
'Antarctica': 'AQ', 
'Argentina': 'AR', 
'American Samoa': 'AS', 
'Austria': 'AT', 
[...] 
}; 

country_codeは「AD」を受け取る必要があります。

どうしたのですか?

+3

を初期化countrylist' 'の宣言を入れ**前**あなたがそれを使用しようとする地点。 – Pointy

答えて

3

問題は、そこから情報を取得しようとした後にcountylistオブジェクトを定義している可能性があります。最初にcountrylistを定義してから、そこから情報を取得する必要があります。

var country = 'Andorra' 

var countrylist = { 
'Andorra': 'AD', 
'United Arab Emirates': 'AE', 
'Afghanistan': 'AF', 
'Antigua and Barbuda': 'AG', 
'Anguilla': 'AI', 
'Albania': 'AL', 
'Armenia': 'AM', 
'Angola': 'AO', 
'Antarctica': 'AQ', 
'Argentina': 'AR', 
'American Samoa': 'AS', 
'Austria': 'AT', 
[...] 
}; 

var country_code = countrylist[country] //put this line of code last 
+0

_ "問題がある可能性があります" _?あなたはそれについては分かりませんか? – Rayon

+0

@Rayonは決して完全に何かを確実にすることはできません – Tucker

0

あなたがcountrylist変数を宣言する前に使用しました。あなたはあなたのcountrylist varibleの下に座るためにcountry_codeの宣言を動かす必要があります。このように:strictモードなし Javascriptを変数巻上と呼ばれているものを何かをするので、あなたがエラーを取得していない

を宣言されています前に

var countrylist = { 
'Andorra': 'AD', 
'United Arab Emirates': 'AE', 
'Afghanistan': 'AF', 
'Antigua and Barbuda': 'AG', 
'Anguilla': 'AI', 
'Albania': 'AL', 
'Armenia': 'AM', 
'Angola': 'AO', 
'Antarctica': 'AQ', 
'Argentina': 'AR', 
'American Samoa': 'AS', 
'Austria': 'AT', 
[...] 
}; 
var country_code = countrylist[country] 
2

あなたは、変数を使用しています。 [For more follow this link ]例えば

:あなたの問題へ

bla = 2 
var bla; 
// ... 

// is implicitly understood as: 

var bla; 
bla = 2; 

とソリューション、それが宣言だ後に変数を使用することで、

var country = 'Andorra' // the input country (I had to throw in the 

apostrophes because of country names such as "Congo Republic of" that would recognise of as a keyword if not kept in apostrophes.) 
var countrylist = { 
'Andorra': 'AD', 
'United Arab Emirates': 'AE', 
'Afghanistan': 'AF', 
'Antigua and Barbuda': 'AG', 
'Anguilla': 'AI', 
'Albania': 'AL', 
'Armenia': 'AM', 
'Angola': 'AO', 
'Antarctica': 'AQ', 
'Argentina': 'AR', 
'American Samoa': 'AS', 
'Austria': 'AT', 
[...] 
}; 
var country_code = countrylist[country] 
関連する問題