javascript - 对象属性在 console.log 中显示为未定义

标签 javascript safari local-storage local-database

我对以下代码有疑问:

var data = {};

$('table tr').each(function() {
  var uid = $('td a', $(this)).attr('href').split('=')[1];

  TTDB.transaction(
    function (tx) {
        tx.executeSql("SELECT id FROM players WHERE uid = ?;", [uid], function (txSub, results) {
          data[uid] = results.rows.item(0).id;
        }, TTDBerrorHandler);
    }
  );
});

$('#member tbody tr').each(function() {
  var uid = $('td a', $(this)).attr('href').split('=')[1];

  console.log(uid); // Returns correctly 1643 as shown below
  console.log(data); // Returns whole object correctly
  console.log(data['1643']); // Returns **undefined**
  console.log(data[uid]); // Returns **undefined**
  console.log(uid); // uid is still correctly set to 1643

  /* Following from Safari console
  1643
  Object
    156: 1
    217: 17
    295: 138
    579: 136
    764: 139
    774: 142
    816: 144
    826: 14
    955: 73
    1096: 137
    1133: 13
    1134: 141
    1232: 140
    1321: 11
    1643: 31
    2307: 143
    __proto__: Object
  undefined
  undefined
  1643
  */
});

这是一个可以正常工作的测试集。

var test = {};
test[156] = 1;
test[1643] = 31;

var testUid = 1643;

console.log(test);
console.log(test['1643']); // Returns correctly 31 as shown below
console.log(test[testUid]); // Returns correctly 31 as shown below

/* This is from Safari console
Object
  156: 1
  1643: 31
  __proto__: Object
31
31
*/

由于基本相同的测试集工作,我猜问题与本地数据库的异步操作有关,但我不知道如何解决这个问题......

更新: 澄清我的问题/我想要达到的目标。

例如,如果我有一个表,我对其进行迭代,然后想添加一些包含数据库中数据的字段。

<table>
  <tr><td class="uid">123<td></tr>
  <tr><td class="uid">234<td></tr>
</table>

然后我想向其中添加新列:

$('table tr').each(function() {
  var uid = $('td.uid', $(this)).text();

  TTDB.transaction(
    function (tx) {
        tx.executeSql("SELECT id FROM players WHERE uid = ?;", [uid], function (txSub, results) {
          // Problem is that because this transaction is asynchronous $(this) is 
          // not defined when this gets executed.
          $(this).append('<td class="id">' + id + '</td>'); 
        }, TTDBerrorHandler);
    }
  );
});

最佳答案

如果您将日志更改为使用 JSON.stringify,您将看到该对象为空。

console.log(uid);
console.log(JSON.stringify(data)); // Returns empty object

使用 JSON.stringify 强制控制台立即读取整个对象,而不是稍后在控制台中展开对象时读取。

您应该将日志记录代码放在 tx.executeSql 回调中,以便在响应到来后记录各个项目。

关于javascript - 对象属性在 console.log 中显示为未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11995200/

相关文章:

javascript - 如何使用 John Papa 风格、Karma 和 Jasmine 数据服务测试 Angular 应用程序?

javascript - 当我按 ctrl 键时 <div> 出现在 textArea 中的光标下方?

javascript - 节点列表 - 'undefined: not bound to any nodes'

ios - 当应用程序在 iOS 中处于后台时,openURL 不起作用

javascript - 修改ajax请求中的全局变量

html - 网站视口(viewport)在 Bootstrap 4 上的 Safari 浏览器上仍然可以缩放和捏合

javascript - mac safari 中的 Gif 动画卡住

android - 打开并显示本地存储的 pdf 文件

javascript - 来自 localstorage 的 JSON 无法在 php 中解码

javascript - 如何检查本地存储数据集中是否存在值?