变量未正确赋值,可能存在作用域问题(getJSON()中的each()中有一个开关的函数)

variable not being assigned correctly, possible scope issue (a function with a switch within each() within getJSON())

本文关键字:getJSON 中的 each 有一个 函数 开关 问题 赋值 作用域 存在 变量      更新时间:2023-09-26

我有一个包含图像路径的变量。根据我接收到的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函数作用域等。我认为我应该能够在函数调用和全局变量声明之前声明函数是对的吗?

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

谢谢你的帮助!提前

交换机正在进行相同的比较(===)。你的变量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节:

如果input等于===操作符定义的clauseSelector,则