如何使用Javascript foreach循环与关联数组对象

时间:2015-08-02 14:27:23

标签: javascript php jquery arrays ajax

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

//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

enter image description here

2 个答案:

答案 0 :(得分:2)

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

如果您想迭代此对象,可以使用

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

如果您使用的是ECMAScript 2015(ES6),则可以使用

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

答案 1 :(得分:0)

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

相关问题