gpt4 book ai didi

使用 Phonegap 全局数组的 Javascript 不起作用

转载 作者:行者123 更新时间:2023-12-02 19:40:11 24 4
gpt4 key购买 nike

我正在创建一个phonegap应用程序来获取联系人并将其保存在数据库中。我在顶部创建了两个空的全局数组,用于保存人员的电话号码和显示名称,稍后将其存储在数据库表中。为了检查联系人是否已成功保存在数组中,我创建了一个 test_data() 函数。

现在我的问题是 test_data() 代码不起作用,日志中没有显示任何值。现在,如果我将该代码从 test_data() 函数移动到 onSuccess() ,它就可以正常工作。这是代码。这不是在JS中声明全局数组的正确方法吗?

<!DOCTYPE html>
<html>
<head>
<title>Contact Example</title>

<script type="text/javascript" charset="utf-8" src="cordova-1.7.0.js"></script>
<script type="text/javascript" charset="utf-8">
var gcont = []; var gphon = [];

// Wait for Cordova to load
//
document.addEventListener("deviceready", onDeviceReady, false);

// Cordova is ready
//
function onDeviceReady() {

// find all contacts with 'Bob' in any name field
var options = new ContactFindOptions();
options.filter="";
options.multiple=true;
var fields = ["displayName", "phoneNumbers"];
navigator.contacts.find(fields, onSuccess, onError, options);
test_data();
}

// onSuccess: Get a snapshot of the current contacts
//
function onSuccess(contacts) {


for(var index=0;index<contacts.length;index++){
gcont[index] = contacts[index].displayName;
gphon[index] = contacts[index].phoneNumbers[0].value;

}


}

function test_data(){
for (z=0;z<gcont.length;z++){
console.log(gcont[z]);}
}




// onError: Failed to get the contacts
//
function onError(contactError) {
alert('Error With Contacts!');
}


</script>
</head>
<body>
<h1>Example</h1>
<p>Find Contacts</p>
</body>
</html>

最佳答案

对 test_data() 的调用在 onDeviceReady() 中不起作用,因为对 contact.find 的 onSuccess 回调是异步的,并且执行 test_data() 时尚未填充数组。

关于使用 Phonegap 全局数组的 Javascript 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10469843/

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