最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - how to use Javascript foreach loop with associative array object - Stack Overflow

programmeradmin2浏览0评论

i have below given array as my ajax response, now i want to append these array values in my html div for this i have used for loop but whats going wrong ? i am getting below output (see attached image)

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

i have below given array as my ajax response, now i want to append these array values in my html div for this i have used for loop but whats going wrong ? i am getting below output (see attached image)

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

Share Improve this question edited Aug 2, 2015 at 15:30 amit gupta asked Aug 2, 2015 at 14:27 amit guptaamit gupta 1,3302 gold badges21 silver badges36 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 6

There is no associative array in javascript, it's a just an object with properties.

If you would like to iterate this object you can use a for...in loop:

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

You can also use a for...of loop with Object.values() to get the value directly:

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

Javascript has no associative arrays. You could loop over the object, but since you are using jQuery anyway you could use each(). If performance matters, use a for loop tho.

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

发布评论

评论列表(0)

  1. 暂无评论