[英]Get n Value from Javascript Array
I'm trying to iterate through a JavaScript Array and display individual object values as alerts. 我正在尝试迭代JavaScript数组并将各个对象值显示为警报。 Basically, the array contains objects of type person
基本上,数组包含person
类型的对象
"person" : {
"id": String,
"name": String,
"address": String
}
And my array is as follows: 我的数组如下:
//This is where I get my array from the code behind. It's not empty. I checked
var obj = JSON.parse(val)
obj.forEach(function (entry) {
console.log(entry);
//This prints the entire array and its objects
});
What I want is not to print the entire array, I want to print: 我想要的不是打印整个阵列,我想打印:
obj.forEach(function (entry) {
console.log(entry[1].name);
console.log(entry[1].address);
//This prints the entire array and its objects
});
What changes should I apply to my code? 我应该对代码进行哪些更改?
Inside the foreach, entry
is just a person element, use: 在foreach中, entry
只是一个person元素,使用:
obj.forEach(function (entry) {
console.log(entry.name);
console.log(entry.address);
});
The function in .forEach can take an index and an element - .forEach中的函数可以使用索引和元素 -
$.each(obj, function(index, element) {
...
});
So you can either use the element directly, or use the index. 所以你可以直接使用元素,也可以使用索引。
If you are not required to use vanilla JS, you can use JQuery: 如果您不需要使用vanilla JS,则可以使用JQuery:
$( obj ).each(function( index ) {
console.log($( this ).name);
console.log($( this ).address);
});
Or 要么
$( obj ).each(function( index ) {
console.log($( obj )[index].name);
console.log($( obj )[index].address);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.