gpt4 book ai didi

javascript - 如何读取/访问名称 :values of Objects stored within an Array?

转载 作者:行者123 更新时间:2023-11-28 18:58:31 25 4
gpt4 key购买 nike

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

我尝试使用 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 - 如何读取/访问名称 :values of Objects stored within an Array?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33086331/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com