【问题标题】:How I can change value varible in a file in another file in javascript如何在javascript中的另一个文件中更改文件中的值变量
【发布时间】:2021-11-16 23:10:41
【问题描述】:

我想在另一个文件中更改 index.js 中的值变量,但我不能这样做,这是我的代码示例

index.js

   var length = 0;
   client.commands.get('join').excute(length);

另一个文件.js

module.exports = {
    name: 'join',
    description: "",
    excute(length){
       length++;
    }

index.js 中的长度是 + 1 = 2,但 anotherfile.js 中的长度不是

我将 anotherfile.js 导入到 index.js

那么我如何改变长度变量的值

非常感谢你,对不起我的英语不好

【问题讨论】:

    标签: javascript node.js variables global-variables module.exports


    【解决方案1】:

    它不起作用,因为 JavaScript 不会通过对其他函数的引用传递具有原始数据类型(例如整数)的变量,而是创建具有不同内存地址的全新变量。改变原始内存位置的唯一方法是传入一个数组或对象,然后 JavaScript 会将指向原始内存位置的指针(即“引用”)传递给函数。

    因此,您必须将 length 的数据类型更改为对象,并将对象的值/长度添加为属性。 excute 函数然后将访问该属性并像这样递增它:

    index.js

    const obj = { length: 0 }
    
    client.commands.get('join').excute(obj);
    

    另一个文件.js

    module.exports = {
        name: 'join',
        description: "",
        excute(obj){
           obj.length++;
        }
    }
    

    请记住,您必须传递整个对象,否则如果您只传递 obj.length,它将简单地复制该值并创建一个设置为该值的全新变量。

    【讨论】:

    • 天哪,它正在工作,非常感谢
    • 随时交配;)
    猜你喜欢
    • 1970-01-01
    • 2021-05-09
    • 2019-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多