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

ami*_*pta 1 javascript php arrays ajax jquery

我有下面给定的数组作为我的 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
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

Ori*_*ori 6

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

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

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

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

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