JavaScript中的调试问题
我需要将国家/地区名称转换为相应的两位数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'。
我做错了什么?
答案 0 :(得分:3)
问题可能是您在尝试从中获取信息后定义了countylist对象。您需要先定义国家/地区列表,然后才能从中查找信息。
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
答案 1 :(得分:2)
您在声明
之前使用过变量您没有收到错误,因为没有严格模式 javascript会执行所谓的变量提升。 [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]
答案 2 :(得分:0)
您在声明之前已使用了countrylist变量。您需要将country_code的声明移到您的countrylist varible下方。像这样:
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]