变量始终记录为NaN

时间:2015-12-27 06:06:38

标签: javascript

有人可以向我解释为什么每次我尝试使用var clients调用NaNconsole.log总是会返回//Imports var inherits = require('util').inherits, MultiServer = require('../classes/servers/multi_server.js'); var clients = 0; function PingServer(servers) { MultiServer.call(this, servers); //Inheritance //Basic server setup this.on('listen', function(params) { console.log("TCP server listening at", params['TCP'].ip + ":" + params['TCP'].port); console.log("Socket.IO server listening at", params['Socket.IO'].ip + ":" + params['Socket.IO'].port); console.log("All systems operational."); }); this.on('error', function(err, source) { console.log("Error in " + source + " server:", err.message); }); //Server behaviour this.on('connect', function(client) { console.log("A client has connected."); var clients = clients + 1; console.log("Client = " + clients); //Basic client setup client.on('disconnect', function() { console.log("A client has disconnected."); var clients = clients - 1; console.log("Clients = " + clients); }); client.on('error', function(err) { console.log("A client has experienced an error:", err.message); }); //Main server behaviour client.on('message', function(msg) { client.send(msg); //Ping reply console.log("Received message:", msg); }); }); } inherits(PingServer, MultiServer); //Inheritance //Exports module.exports = PingServer;

getNewImageData

2 个答案:

答案 0 :(得分:1)

使用var声明的变量是函数作用域并在JavaScript中提升。每次键入var clients时,它都会在当前函数的范围内创建一个变量。

本声明:

var clients = 0;

首先声明变量clients,然后为其赋值0

然后你正在写

(function(){
  var clients = clients + 1;
  console.log("Client = " + clients);
})

然而,这又做了同样的事情再次:它声明了一个 new 变量clients并将其范围扩展到该函数。这个新的clients变量与初始变量不同。在此功能中,它是阴影(即无法访问)。实际上,clients在函数中是undefined

提升意味着变量声明会自动移动到函数的顶部。

这意味着声明

var clients = clients + 1;
函数中的

等同于

var clients = undefined + 1;

var clients = NaN;

但是,如果您删除了var关键字,则不会创建新变量,而是使用旧变量

var clients = 0;

(function(){
  clients = clients + 1; // clients = 0 + 1 === 1;
  console.log("Client = " + clients); // "Client = 1"
})

clients = clients + 1最好写成clients++

答案 1 :(得分:0)

您有 clients 变量的多个声明。

更改此

var clients = clients + 1;

clients = clients + 1;

&安培;此

var clients = clients - 1;

clients = clients - 1;