如何访问名称:randomImage.images数组中存储的每个Object的值?
我尝试使用 for in 循环(请参阅randomImage.imagePicker方法以供参考),但我得到的输出是:
0[object Object]
1[object Object]
2[object Object]
3[object Object]
(function() {
var randomImage = {
images : [
{ 'image 1' : 'http://placehold.it/100x100'},
{ 'image 2' : 'http://placehold.it/200x200'},
{ 'image 3' : 'http://placehold.it/300x300'},
{ 'image 4' : 'http://placehold.it/400x400'}
],//images Array
imagePicker : function () {
for (var k in this.images ) {
console.log(k+this.images[k]);
}
}//imagePicker Method
}//randomImage Object
randomImage.imagePicker()
})()
答案 0 :(得分:1)
不要使用for...in
循环来迭代数组。
您可以使用Object.keys
获取对象的可枚举属性。
randomImage.images.forEach(function(obj) {
var prop = Object.keys(obj)[0],
value = obj[prop];
console.log(prop, value);
});
答案 1 :(得分:1)
一个解决方案是这样的:
(function() {
var randomImage = {
images : [
{ 'image 1' : 'http://placehold.it/100x100'},
{ 'image 2' : 'http://placehold.it/200x200'},
{ 'image 3' : 'http://placehold.it/300x300'},
{ 'image 4' : 'http://placehold.it/400x400'}
],//images Array
imagePicker : function () {
for (var k in this.images ) {
var curImg = this.images[k];
var key = Object.keys(curImg)[0];
console.log(k+this.images[k]);
msg = k + ' : ' + key + ' => ' + curImg[key];
document.getElementById('el').innerHTML+='<div>'+msg+'<div>';
}
}//imagePicker Method
}//randomImage Object
randomImage.imagePicker()
})()
&#13;
<div id ='el'><div>
&#13;
答案 2 :(得分:1)
您可以使用forEach
循环访问这些值。
this.images.forEach(function(image){
for(var key in image) {
console.log('key', key);
console.log('value', image[key]);
}
});
答案 3 :(得分:0)
使用console.log(k,this.images [k]); (逗号而非加号)
您将获得输出:
0 Object {image 1: "http://placehold.it/100x100"}
1 Object {image 2: "http://placehold.it/200x200"}
2 Object {image 3: "http://placehold.it/300x300"}
3 Object {image 4: "http://placehold.it/400x400"}
答案 4 :(得分:0)
还有一个选择。对于现在的结构,您需要两个循环。一个遍历图像阵列,另一个循环访问密钥。
imagePicker : function () {
for ( var i=0, len=this.images.length; i<len; i++ ) {
var imgObj = this.images[ i ];
for ( var key in imgObj ) {
console.log( key + imgObj[ key ] );
}
}
}
虽然我想知道你是否可以通过使用数组来存储图像网址。
images: [
'http://placehold.it/100x100',
'http://placehold.it/200x200',
'http://placehold.it/300x300',
'http://placehold.it/400x400'
]
答案 5 :(得分:0)
var images = [
{
name: 'image 1',
url: '//placehold.it/100x100'
}
...
]
更好的解决方案是设计更好的数据模型,如:
function() {
var i = 0;
var len = this.images.length;
for (i; i < len; i++) {
var oImage = this.images[i];
console.log(oImage.url, oImage.name);
}
}
并访问图片名称和网址,如:
<input type="submit" value="some value" onclick="return function name()" />
<script>
function name(){
var htmlElement = //i want to get here clicked input's value
return false;
}
</script>