变量未正确分配,可能的范围问题(getJSON()中每个()内有一个开关的函数)

时间:2013-06-20 07:11:46

标签: javascript jquery json scope each

我有一个包含图像路径的变量。根据我为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”参数。事实上,如果我确实声明了一个参数,它就会中断。但我猜这是因为它创建了一个新的局部变量,我是对的吗?

感谢您的帮助!提前

1 个答案:

答案 0 :(得分:2)

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

由于类型不同,交换机正在评估'1' === 1,其评估为false。

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

        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节:

  

如果输入等于===运算符定义的clauseSelector,则