简体   繁体   English

如何在 Node.JS 中使用这个 function?

[英]How do I use this function in Node.JS?

//tools.js
function randomString() {
    var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
    var string_length = 8;
    var randomstring = '';
    for (var i=0; i<string_length; i++) {
        var rnum = Math.floor(Math.random() * chars.length);
        randomstring += chars.substring(rnum,rnum+1);
    }
    return randomString;
}
exports.randomString = randomString();


//test.js
var tools = require('./tools');
console.log(tools.randomString());

But when I run it, I get this:但是当我运行它时,我得到了这个:

[Function: randomString]

How do I actually make it spit out a random string?我实际上如何让它吐出一个随机字符串?

exports.randomString = randomString;

or或者

exports.randomString = function() {....}

Don't know node.js in detail.不详细了解node.js。 But

exports.randomString = randomString();

already calls the function and assigns the result to exports.randomString.已经调用了 function 并将结果分配给 export.randomString。

To assign the reference you should take away the braces.要分配参考,您应该拿走大括号。

Second Bug:第二个错误:

return randomString;

needs to be (watch the case)需要(看案例)

return randomstring;

as this is the variable where you build and store your random string.因为这是您构建和存储随机字符串的变量。

Are yor sure that your accepted answer fully resolves your problem?您确定您接受的答案完全解决了您的问题吗?

If you do如果你这样做

exports.randomString = randomString();

then you call the random string function exactly once and assign the result to exports.randomString.然后你只调用一次随机字符串 function 并将结果分配给exports.randomString。

Please check and call multiple times请检查并多次致电

console.log(tools.randomString());

For more advice please read my other answer above.如需更多建议,请阅读我上面的其他答案。 Hope I could help.希望我能帮上忙。

use a different name for your result.为您的结果使用不同的名称。 one which isn't the same as your function's name.一个与您的函数名称不同的名称。

the variable randomstring contains your accumulated result but you return randomString which is just off it by case and is the name of the function.变量randomstring包含您的累积结果,但您返回randomString只是按大小写,是 function 的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM