首页 > 解决方案 > 从 file2.js 文件的 func2 调用 file1.js 的函数 func1,并且 func1 使用在 file1.js 中声明的全局变量

问题描述

让我重写这个问题。我已经测试了代码,问题应该是可重现的。有两个html文件,test1.html和test2.html,还有两个js文件:file1.js和file2.js。

测试1.html:

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
    <p>Hello, It's test1 page!</p>
    <button onclick = "func0()">populate contacts</button>
    <script src="file1.js"></script>
</body>
</html>

如您所见,file1.js 包含在 test1.html 中。

测试2.html:

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
    <p>Turn to test2 page now!</p>
    <button onclick = "func2()">Try me</button>
    <script src="file1.js"></script>
    <script src="file2.js"></script>
</body>
</html>

file1.js 和 file2.js 都包含在 test2.html 中。

文件 1.js:

"use strict";

var contacts = [];

function func0() {
    contacts.push('mike');
    contacts.push('tom');
    contacts.push('joe');
    window.location.replace("test2.html");
}

function func1(msgType, uuid) {
    if(isArrayEmpty(contacts)) {
        alert("contacts is empty");
        return;
    }
    contacts.forEach(function(contact) {
        console.log(contact + " sends msg with type = " + msgType + ", and msg id = " + uuid);
    });
}

function isArrayEmpty(array) {
    if (!Array.isArray(array) || !array.length) {
        return true;
    }
    return false;
}

文件2.js:

"use strict";

function func2() {
    func1('OPEN', '1234');
}

如您所见,file1.js 的 func1 被 file2.js 的 func2 调用。但是在 file1.js 中声明的变量 contacts 是空的。因此,实际上并没有完成接触循环。联系人不应为空,因为 file1.js 的 func0 为其填充了值。通过单击 test1.html 中的“填充联系人”按钮调用 func0。

这实际上发生在我阅读的代码中。

在这里寻求答案。

2021 年 3 月 31 日编辑:有人可以帮忙吗?

标签: javascriptfunctionvariablesglobal

解决方案


我认为你有一个对象类型错误,因为 contact var 是一个对象({})你不能使用.push它的方法,因为对象没有它。我建议您使用数组,而不是使用常规对象:var contacts = [];


推荐阅读