如何访问在randomImage.images数组中存储的每个对象的name:values?

我尝试使用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()

})()

最佳答案

一种解决方案是这样的:



(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()

})()

<div id ='el'><div>

关于javascript - 如何读取/访问名称:存储在数组中的对象的值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33086331/

10-12 05:14