1

我有一个包含图像路径的变量。根据我收到的 JSON 对象的整数值,该变量应该获得不同的路径。

但是,由于某些原因,在下面的函数中,分配给变量的路径仍然是全局声明的路径,尽管我知道我的 JSON 对象正在为 switch 语句返回正确的整数这一事实。看看下面的代码:

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();

我对javascript函数范围等有点陌生。我是否认为我应该能够在函数调用和全局变量声明之前声明函数?

我也觉得奇怪的是,我不必在 spawnThumbnails 函数声明中声明“thumbimage”参数。事实上,如果我确实声明了一个参数,它就会中断。但我猜这是因为它创建了一个新的局部变量,对吗?

谢谢你的帮助!提前

4

1 回答 1

2

交换机正在执行相同的比较 ( ===)。你的变量thumbtype是一个字符串,即使它有一个数值,它仍然是一个字符串。

由于类型不同,开关正在评估'1' === 1哪个评估为假。

将其与字符串进行比较,而不是整数(注意引号)

        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;
        }

或者将字符串转换为整数,然后将开关作为数字进行比较。

thumbtype = parseInt(thumbtype);

来自 ECMA 262 语言规范,第 12.11 节:

如果输入等于 === 运算符定义的子句选择器,则

于 2013-06-20T07:20:58.147 回答