Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/369.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 试图访问作为字符串的对象文字键_Javascript_Object Literal - Fatal编程技术网

Javascript 试图访问作为字符串的对象文字键

Javascript 试图访问作为字符串的对象文字键,javascript,object-literal,Javascript,Object Literal,我尝试使用字符串作为对象文本中的键,然后在将该字符串添加到HTML li元素中的数据属性的函数中使用该字符串。其基本思想是创建一个用户id,然后访问特定用户进行更新/删除。“创建”部分工作正常 首先,我需要将信息输入到我的li元素中,以便单击可以获得我想要的id。下面的代码可以工作,但这只是因为我在对象中包含了id。在对象内部复制字符串(userguid键)只是为了使用它,这看起来既愚蠢又错误 users = { "0c7270bd-38e8-4db2-ae92-244de019c543":

我尝试使用字符串作为对象文本中的键,然后在将该字符串添加到HTML li元素中的数据属性的函数中使用该字符串。其基本思想是创建一个用户id,然后访问特定用户进行更新/删除。“创建”部分工作正常

首先,我需要将信息输入到我的li元素中,以便单击可以获得我想要的id。下面的代码可以工作,但这只是因为我在对象中包含了id。在对象内部复制字符串(userguid键)只是为了使用它,这看起来既愚蠢又错误

users = {
  "0c7270bd-38e8-4db2-ae92-244de019c543": {
    datecreated: "2013-10-15",
    email: "jimmy@example.com",
    firstname: "Jimmy",
    lastname: "Smith",
    username: "jimmysmith",
    password: "foobar",
    notify: "barbour@4j.lane.edu",
    userguid: "0c7270bd-38e8-4db2-ae92-244de019c543"
  },
  "0c7270bd-38e8-4db2-ae92-244de019mju7": {
    datecreated: "2013-10-16",
    email: "mary@example.com",
    firstname: "Mary",
    lastname: "Jones",
    username: "maryjones",
    password: "foobar2",
    notify: "barbour@4j.lane.edu",
    userguid: "0c7270bd-38e8-4db2-ae92-244de019mju7"
  }
};
使用它的函数:

displayUserList = function() {
  var newHTML;
  users = JSON.parse(localStorage["users"]);
  newHTML = [];
  $.each(users, function(index, user) {
    return newHTML.push('<li data-userguid="' + user.userguid + '" data-firstname="' + user.firstname + '"><span class="userfullname">' + user.firstname + ' ' + user.lastname + '</span></li>');
  });
  /*
    jquery css going on here
  */
};
我开始觉得我缺少了使用对象文字的基本规则,但我在搜索中没有找到它

谢谢你的帮助


Charlie Magee

使用
$在对象上迭代时。每个
,索引参数都会接收键,因此您可以执行以下操作:

newHTML.push('<li data-userguid="' + index + '" data-firstname="' + user.firstname + '"><span class="userfullname">' + user.firstname + ' ' + user.lastname + '</span></li>');
newHTML.push(“
  • “+user.firstname+”+“+user.lastname+”
  • ”);

    您不需要在此语句上返回
    return
    $。each()
    对返回值所做的唯一一件事就是测试它的
    ==false
    ——如果是,循环结束。

    索引将是关键。你为什么要将密码存储为纯文本客户端?该死!我尝试了[索引],但没有索引。显然,我们还在努力找出括号的正确位置。这很好。当你想创建一个数组文字时,你可以用括号括起来。当您想使用名称作为索引来访问数组或对象的元素时,可以在名称后面加括号。
    
    newHTML.push('<li data-userguid="' + index + '" data-firstname="' + user.firstname + '"><span class="userfullname">' + user.firstname + ' ' + user.lastname + '</span></li>');