在if语句中设置变量的值。然后在声明之外使用它

时间:2016-06-09 12:38:12

标签: javascript node.js variables twitch

所以当用户在chatDisallowed数组中输入聊天内容时,我一直试图为变量设置一个值。但是,我无法获得if语句之外的变量值。有人可以帮帮我吗?

代码如下:



client.on('chat', function(channel, user, message, self) {
	for (var i = 0; i < 3; i++) {
		
		if(message.indexOf(linksDisallowed[i]) >= 0) {
			 var timeoutUser = 1;
			//console.log("Link detected!");
			//client.say("dunkstormen", "Ahem! " + user.username + " are you allowed to post links?!");
		} else {
			var timeoutUser = 0;
			//console.log("No link detected!");
			//client.say("dunkstormen", "Hello, " + user.username);
		}
		
	}
	
	if(timeoutUser == 1) {
		console.log("Timing out " + user.username);
	} else {
		timeoutUser == 0
		console.log("Not timing out " + user.username);
	}
});
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

你所展示的代码应该有效,因为在函数中定义var的位置并不重要,因为var声明被提升并且变量的范围限定为函数级别,而不是块级别。

其他因素导致您的问题,而不是变量的声明。

如何使代码更具可读性,可以在函数入口处声明变量:

client.on('chat', function(channel, user, message, self) {
    var timeoutUser;
    for (var i = 0; i < 3; i++) {

        if(message.indexOf(linksDisallowed[i]) >= 0) {
             timeoutUser = 1;
            //console.log("Link detected!");
            //client.say("dunkstormen", "Ahem! " + user.username + " are you allowed to post links?!");
        } else {
            timeoutUser = 0;
            //console.log("No link detected!");
            //client.say("dunkstormen", "Hello, " + user.username);
        }

    }

    if(timeoutUser == 1) {
        console.log("Timing out " + user.username);
    } else {
        timeoutUser == 0
        console.log("Not timing out " + user.username);
    }
});

答案 1 :(得分:-1)

client.on('chat', function(channel, user, message, self) {
    var timeoutUser = 0;

    for (var i = 0; i < 3; i++) {
        if(message.indexOf(linksDisallowed[i]) >= 0) {
            timeoutUser = 1;
            // console.log("Link detected!");
            // client.say("dunkstormen", "Ahem! " + user.username + " are you allowed to post links?!");
        } else {            
            // console.log("No link detected!");
            // client.say("dunkstormen", "Hello, " + user.username);
        }

    }

    if(timeoutUser == 1) {
        console.log("Timing out " + user.username);
    } else {
        console.log("Not timing out " + user.username);
    }
});