[英]how to use Javascript foreach loop with associative array object
我在下面給出了數組作為我的 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 中沒有關聯數組,它只是一個具有屬性的對象。
如果你想迭代這個對象,你可以使用for...in
循環:
for (var key in result)
{
console.log(result[key]);
$("#error_div").append(result[key]);
}
您還可以使用帶有Object.values()
的for...of
循環來直接獲取值:
for (let value of Object.values(result))
{
console.log(value);
$("#error_div").append(value);
}
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>');
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.