【问题标题】:Javascript Foreach loop over array of objects?Javascript Foreach循环对象数组?
【发布时间】:2015-03-26 22:36:37
【问题描述】:

我目前正在使用 Ajax 重复地从使用其 API 的应用程序中提取控制台日志。在 PHP 中执行返回值的 var_dump() 时,它是一个对象数组,我需要循环并提取值。

这在 PHP 中当然很简单,但是像我一样缺乏 Javascript 经验,我无法通过 for 或 foreach 循环来解决这个问题。我已将 console.log 与 Developer Console 一起使用,并且内容在那里,但对于如何循环访问的任何帮助将不胜感激。

JS/Ajax:

function getConsoleMessages()
{
    var messageBox = document.getElementById("console_message");

    // Clear the message box contents
    //messageBox.value = '';

    $.ajax({
        type: "POST",
        url: "ajax.php",
        data: { 'action': 'getConsoleMessages' },
        dataType: 'json',
        success: function(data)
        {
            var messages = data['message'];

            messages.forEach( function (item)
            {
                var x = item.Contents;
                console.log(x);
            });
        },
        error: function(XMLHttpRequest, textStatus, errorThrown)
        { 
            alert("Status: " + textStatus); alert("Error: " + errorThrown); alert("Message: " + XMLHttpRequest.responseText);
        }
    });
};

PHP 处理程序:

case "sendConsoleMessage":
{
    $message = $_POST["message"];

    if (empty($message))
    {
        $response['status'] = "failed";
        $response['message'] = "Command parameter was not received.";
    }
    else
    {
        $amp->sendConsoleMessage($message);

        $response['status'] = "success";
        $response['message'] = $message;
    }

    echo json_encode($response);

    break;
}

PHP var_dump:

object(stdClass)[2]
  public 'result' => 
    array (size=40)
      0 => 
        object(stdClass)[3]
          public 'Timestamp' => string '/Date(1422419818830-0500)/' (length=26)
          public 'Source' => string 'Console' (length=7)
          public 'Type' => string 'Console' (length=7)
          public 'Contents' => string 'Assigned anonymous gameserver Steam ID [A:1:721403909:5132].' (length=60)
      1 => 
        object(stdClass)[4]
          public 'Timestamp' => string '/Date(1422419819038-0500)/' (length=26)
          public 'Source' => string 'Console' (length=7)
          public 'Type' => string 'Console' (length=7)
          public 'Contents' => string 'VAC secure mode is activated.' (length=29)
      2 => 
        object(stdClass)[5]
          public 'Timestamp' => string '/Date(1422419819145-0500)/' (length=26)
          public 'Source' => string 'Console' (length=7)
          public 'Type' => string 'Console' (length=7)
          public 'Contents' => string 'tf_server_identity_account_id not set; not logging into registered account' (length=74)

【问题讨论】:

  • 我使用 console.log 将返回值打印到开发者控制台并将其添加到原始消息中,但是它似乎丢失了格式:/
  • 来自 MDN Array.forEach
  • 我刚刚用我的函数更新了原始帖子并使用了数组 forEach() 但我只是在 var x = item.Contents; 上得到“未定义不是函数”;
  • 谢谢你:),检查我的回答,我认为这会有所帮助

标签: javascript php arrays for-loop foreach


【解决方案1】:

通过查看您的数据, 我想你想做标准

for(i;i<count;i++)
{

   //then and this is the part I believe you are missing:
    for (variable in object) 
    {  str += variable + ":" + object[variable] ;  }

}

见: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

【讨论】:

    【解决方案2】:

    语法:

    for ([start]; [condition]; [final-expression])
        statement
    

    规则:

    Traditional way of iterating over arrays.
    Can use var, but scope is always the complete surrounding function.
    

    例子:

    var arr = [ "a", "b", "c" ];
    for(var i=0; i < arr.length; i++) {
        console.log(arr[i]);
    }
    

    【讨论】:

    【解决方案3】:

    试试这个:

    function getConsoleMessages()
    {
        var messageBox = document.getElementById("console_message");
    
        // Clear the message box contents
        //messageBox.value = '';
    
        $.ajax({
            type: "POST",
            url: "ajax.php",
            data: { 'action': 'getConsoleMessages' },
            dataType: 'json',
            success: function(data)
            {
                var messages = data['message']['result'];
    
                messages.forEach( function (item)
                {
                    var x = item.Contents;
                    console.log(x);
                });
            },
            error: function(XMLHttpRequest, textStatus, errorThrown)
            { 
                alert("Status: " + textStatus); alert("Error: " + errorThrown); alert("Message: " + XMLHttpRequest.responseText);
            }
        });
    };
    

    【讨论】:

    • 这一行:var messages = data["result"];
    • 我试过但没用,“结果”什么都不是。我刚刚更新了我的 OP 以显示发送响应的 php 代码,您可以看到“消息”是我放置结果内容的位置。
    • 对此很抱歉,但如果这是发送 ajax 响应的 php 处理程序,那么您将在对象内发送 message,您应该能够通过以下方式接收它:var message = data["message"]; console.log(message);
    • 我实际上如何遍历每个值?我想自己手动记录每个“来源”和“内容”值,这就是问题所在。感谢您迄今为止的帮助!
    • 好吧,如果该数组在 php 处理程序发送的消息变量中,我想我更了解你的 sn-p,然后试试这个:var messages = data['message']['result'];
    猜你喜欢
    • 1970-01-01
    • 2013-05-20
    • 2020-10-31
    • 1970-01-01
    • 2016-10-31
    • 2012-04-05
    • 2021-11-29
    • 2016-10-28
    • 2015-10-15
    相关资源
    最近更新 更多