如何在Node JS中定义对象

时间:2020-03-23 07:52:03

标签: javascript node.js express

我正在尝试为对象分配值,但是当我尝试显示它时,它总是返回[]。 这是我的一部分代码

const exspress = require("express");
const aplication = exspress();
//body parser for informaton monggo
const bodyparser = require("body-parser");
//configuration for node aplication
aplication.use(
  bodyparser.urlencoded({
    extended: false
  })
);
const mongose = require("mongoose");

const router = exspress.Router();

const PingModel = mongose.model("Ping");

const ping = require("ping");
var tcpp = require("tcp-ping");     
var obj = Array();
        var a = 0;
        var b = pingtime;
        for(a; a<b; a++){
        ping.promise.probe(host).then(function(data) {
            const storePing = new PingModel();
            storePing.hostPing = host;
            storePing.hostIp = data.numeric_host;
            if (data.alive) {
              storePing.hostStatus = "Ok";
            } else {
              storePing.hostStatus = "Not_ok";
            }
            if (data.alive) {
              storePing.hostLatency = "true";
            } else {
              storePing.hostLatency = "false";
            }
            storePing.save();
            window.obj = storePing
            // return this.obj[a] = storePing;
          });
          console.log(obj);
        }
 module.exports = router;

你们能告诉我如何定义一个对象并用在单独的代码/函数中使用它的数据/值填充它吗?

1 个答案:

答案 0 :(得分:0)

尝试将window.obj更改为obj,因为您的obj只是一个变量,它不在window对象上

此外,在声明对象时,您已将其声明为Array。如果您想要一个Object,则可以使用var obj = {};,尽管无论如何都可以使用storePing

重新分配它

此外,您还需要将console.log移至promise的then回调中,因为它具有异步代码-有时,您的console.log会在then的诺言回调已执行,因此obj尚未具有您期望的值

-

的行很长
const router = exspress.Router();

const PingModel = mongose.model("Ping");

const ping = require("ping");
var tcpp = require("tcp-ping");     
var obj = {}; // NOTE, object instead of array, though this gets reassigned anyway, so doesn't really matter
        var a = 0;
        var b = pingtime;
        for(a; a<b; a++){
        ping.promise.probe(host).then(function(data) {
            const storePing = new PingModel();
            storePing.hostPing = host;
            storePing.hostIp = data.numeric_host;
            if (data.alive) {
              storePing.hostStatus = "Ok";
            } else {
              storePing.hostStatus = "Not_ok";
            }
            if (data.alive) {
              storePing.hostLatency = "true";
            } else {
              storePing.hostLatency = "false";
            }
            storePing.save();
            obj = storePing // <-- NOTE, no window object

            console.log(obj); // <-- NOTE, logging inside the then callback
            // return this.obj[a] = storePing;
          });
        }
 module.exports = router;