Javascript 变量分配不正确,可能存在范围问题(getJSON()中每个()内都有一个开关的函数)
我有一个包含图像路径的变量。根据我收到的JSON对象的整数值,这个变量应该得到不同的路径 然而,在下面的函数中,由于某种原因,分配给变量的路径仍然是全局声明的路径,尽管事实上我知道我的JSON对象正在为switch语句返回正确的整数。请看下面的代码:Javascript 变量分配不正确,可能存在范围问题(getJSON()中每个()内都有一个开关的函数),javascript,jquery,json,scope,each,Javascript,Jquery,Json,Scope,Each,我有一个包含图像路径的变量。根据我收到的JSON对象的整数值,这个变量应该得到不同的路径 然而,在下面的函数中,由于某种原因,分配给变量的路径仍然是全局声明的路径,尽管事实上我知道我的JSON对象正在为switch语句返回正确的整数。请看下面的代码: function spawnThumbnails() { $.getJSON('scripts/get_thumbs.php', function(data){ $.each(data, function(thumb, t
function spawnThumbnails() {
$.getJSON('scripts/get_thumbs.php', function(data){
$.each(data, function(thumb, thumbInfo){
var thumbimage;
// If I create local thumbimage var like so,
//the image below turns is undefined
// But if local thumbimage var is not declared,
// the value defaults to globally declared value of arctic.svg
var thumbtype = thumbInfo.type;
alert(thumbtype); // this will alert correct type (an integer)
switch(thumbtype){
case 1: thumbimage = 'graphics/thumbs/arctic.svg'; break;
case 2: thumbimage = 'graphics/thumbs/savan.svg'; break;
case 3: thumbimage = 'graphics/thumbs/trop.svg'; break;
case 4: thumbimage = 'graphics/thumbs/tundra.svg'; break;
case 5: thumbimage = 'graphics/thumbs/ocea.svg'; break;
}
$("#thumbtest").append('<img src="' + thumbimage + '">');
// returning as the default image or undefined
}); //end each
}); // end json
}
var thumbimage = 'graphics/thumbs/artic.svg'; // default image
// I have tried placing the function definition here as well,
// but there is no difference. Should there be?
spawnThumbnails();
函数生成缩略图(){
$.getJSON('scripts/get_thumbs.php',函数(数据){
$.each(数据、功能(thumb、thumbInfo){
指纹图像;
//如果我像这样创建本地thumbimage变量,
//下面的图像未定义
//但如果未声明本地thumbimage变量,
//该值默认为arctic.svg的全局声明值
var thumbtype=thumbInfo.type;
警报(thumbtype);//这将警报正确的类型(整数)
开关(指型){
案例1:thumbimage='graphics/thumbs/arctic.svg';break;
案例2:thumbimage='graphics/thumbs/savan.svg';break;
案例3:thumbimage='graphics/thumbs/trop.svg';break;
案例4:thumbimage='graphics/thumbs/tundra.svg';break;
案例5:thumbimage='graphics/thumbs/ocea.svg';break;
}
$(“#拇指测试”)。附加(“”);
//作为默认图像返回或未定义
})//结束每一个
});//结束json
}
var thumbimage='graphics/thumbs/artic.svg';//默认图像
//我也尝试过将函数定义放在这里,
//但是没有区别。应该有吗?
生成缩略图();
我对javascript函数范围之类的东西有点陌生。我认为应该能够在函数调用和全局变量声明之前声明函数,对吗
我还发现奇怪的是,我不必在spawnThumbnails函数声明中声明“thumbimage”参数。事实上,如果我声明了一个参数,它就会中断。但我猜这是因为它创建了一个新的局部变量,对吗
谢谢你的帮助!事先,开关正在进行相同的比较(
=
)。变量thumbtype
是一个字符串,即使它有一个数值,它仍然是一个字符串
开关正在计算'1'==1
,由于类型不同,其计算结果为false
将其与字符串比较,而不是与整数比较(注意引号)
或者,将字符串转换为整数,并将开关保留为数字进行比较
thumbtype = parseInt(thumbtype);
ECMA 262语言规范第12.11节:
如果输入等于由===运算符定义的子句选择器,则
确保任何
案例
s匹配…?@deceze是的!他们不匹配。。。接得好!啊,是的!天才。当然,正如@deceze所说,这些案例并不匹配。在这之后它工作得很好!非常感谢。我用了pareseInt方法。现在无论我是否创建thumbimage的局部变量,它都是一样的。很高兴它能工作:)这是一个很容易犯的错误,因为在某些语言中,开关只是一个相等比较,而不是相同的。
thumbtype = parseInt(thumbtype);