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

问题描述 投票:0回答:2

我在给定的数组下面给出了我的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

javascript php jquery arrays ajax
2个回答
3
投票

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);
}

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

© www.soinside.com 2019 - 2024. All rights reserved.