【问题标题】:how to use Javascript foreach loop with associative array object如何使用带有关联数组对象的 Javascript foreach 循环
【发布时间】:2015-08-02 14:27:22
【问题描述】:

我在下面给出了数组作为我的 ajax 响应,现在我想将这些数组值附加到我的 html div 中,因为我已经使用了 for 循环但是出了什么问题?我得到低于输出(见附图)

//Array from php page
Array ( 
[FirstName] => Please enter your first name 
[LastName] => Please enter last name 
[Email] => This e-mail address is already associated to another account. 
[ConfirmPassword] => Passwords do not match 
)

//jquery
success:function(result){
for (var i = 0; i < result.length; i++) 
{
  console.log(result[i]);
  $("#error_div").append(result[i]);
}
  }

//want this output to append in div
Please enter your first name 
Please enter last name 
This e-mail address is already associated to another account.
Passwords do not match

【问题讨论】:

    标签: javascript php jquery arrays ajax


    【解决方案1】:

    javascript中没有关联数组,它只是一个有属性的对象。

    如果你想迭代这个对象,你可以使用 for...in 循环:

    for (var key in result) 
    {
      console.log(result[key]);
      $("#error_div").append(result[key]);
    }
    

    您也可以使用for...of 循环和Object.values() 直接获取值:

    for (let value of Object.values(result)) 
    {
      console.log(value);
      $("#error_div").append(value);
    }
    

    【讨论】:

    • for(let key of Object.keys(obj))
    【解决方案2】:

    Javascript 没有关联数组。您可以遍历该对象,但由于您使用的是 jQuery,因此您可以使用 each()。如果性能很重要,请使用 for 循环。

    var values = {
        'FirstName': 'Please enter your first name ',
        'LastName': 'Please enter last name ',
        'Email': 'This e-mail address is already associated to another account. ',
        'ConfirmPassword' : 'Passwords do not match '
    };
    
    var errors = $('#error_div');
    $.each(values, function( index, value ) {
      errors.append(value);
      errors.append('<br>');
    });
    

    JSFiddle

    【讨论】:

    • 它不起作用,请参阅我的问题中的附图,使用您的答案后我明白了。
    猜你喜欢
    • 2015-03-26
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    • 2014-10-30
    • 1970-01-01
    • 2016-09-09
    • 1970-01-01
    • 2019-08-15
    相关资源
    最近更新 更多