Javascript在函数内声明一个全局变量,带有参数[duplicate]

问题描述 投票:1回答:1

问题:我想在函数内部创建一个变量作为全局变量

这有效:

var x;
function myFunction() {
    x = 999;
}
myFunction();
console.log(x);

但是这个在尝试从API Result声明一个全局变量时不起作用

webOS.service.request(url, {
    onSuccess: function (data) {
        var serial = data.idList[0].idValue;
        var udid = serial; // This is the variable that I want
        callback(udid); // Trying to get this udid out of this API call
},
});

var sn;
function callback(udid) {
    sn = udid; // I want this as my global variable
}
callback(udid); // produces an error which says udid not defined
console.log(sn); // undefined

如何将var sn作为全局变量?提前致谢

javascript function api callback global-variables
1个回答
0
投票

这是因为udid没有在你调用callback的范围内定义 - 你在callback函数中调用onSuccess,所以你不需要再次调用它。你还需要将你的console.log放在你的callback函数中:

webOS.service.request(url, {
    onSuccess: function (data) {
        var serial = data.idList[0].idValue;
        var udid = serial; // This is the variable that I want
        callback(udid); // Trying to get this udid out of this API call
    },
});
var sn;
function callback(udid) {
    sn = udid; // I want this as my global variable
    console.log(sn);
}
© www.soinside.com 2019 - 2024. All rights reserved.