gpt4 book ai didi

javascript - 如何将javascript变量导出到node js

转载 作者:太空宇宙 更新时间:2023-11-04 02:14:13 25 4
gpt4 key购买 nike

我有一个 html 文件,它调用 JavaScript 函数来获取用户输入的 6 位数字。

<html>
<head>
<script src="ho.js"></script>
<h1>Sample</h1>
</head>
<body>
<input type="tel" id="realOTP" placeholder="Enter Your OTP" maxlength="6">
<input type="submit" value="Use OTP" onclick="compute()">
</body>
</html>

这是定义该函数的 ho.js javascript 文件。

var a=10, arr=[];
var exports = module.exports = {};
function compute() {
rOTP = document.getElementById('realOTP').value;
if (rOTP.length == 0) {
alert('Enter a value');
return;
};
arr = String(rOTP).split("");
console.log("Entered OTP -> " + arr);
return arr;
}
exports.array = compute.arr;//what should come here?
exports.r = a;
console.log("a:" +a);
exports.fun =function(){
console.log("in function");
var mes = require("./ho").r;
console.log("mes:"+mes);
var mes2 = require("./ho").array;
console.log("mes2:"+mes2);
}

是否可以将javascript函数的返回值(本例中为“arr”)导出到类似于全局变量a=10的node js导出函数中。这是我的主 Node 文件,我通过浏览器获取“arr”的值后调用它。

hoh.js

var call = require("./ho");
console.log("hoh:" +call.r);
call.fun();

这是我运行 hoh.js 时得到的输出:

C:\Users\Balajee\Desktop\project\Ultro>node hoh.js
a:10
hoh:10
in function
mes:10
mes2:undefined

最佳答案

exports.arr = arr;

将导出数组。但数组在计算中被重新分配。如果compute() 改变数组,您将能够在导出的数组中访问其内容。

arr = String(rOTP).split(""); 更改为 arr.push.apply(arr, String(rOTP).split("")); 以便 computer() 改变 a 而不是重新分配它。

或者,导出 getter

或者,您可以导出一个 getter,这将允许您根据需要继续重新分配 arr。此代码示例也可以使用 ES6 胖箭头语法编写;我只是假设你只能使用 ES5。

exports.getArr = function() { return arr; }

关于javascript - 如何将javascript变量导出到node js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36506679/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com