当前位置:优学网  >  在线题库

这段代码可以简化吗?

发表时间:2022-06-17 17:43:56 阅读:622

不想用循环

const path = require("path");
const os = require("os");
let localhost;
try {
  const network = os.networkInterfaces();
  for (let i in network) {
    for (let j in network[i]) {
      const val = network[i][j];
      if (val.family === "IPv4" && val.address !== "127.0.0.1") {
        localhost = val.address;
        break;
      }
    }
  }
} catch (e) {
  localhost = "http://localhost";
}
🎖️ 优质答案
  • 一句话解决:

    localhost = Object
        .values(network)
        .flat()
        .find(it => it.family === "IPv4" && it.address !== "127.0.0.1")
        ?.address

    另外,我记得 family 的取值是 46,没有 "IPv4" 吧?

  • 相关问题