我有一个对象数组。
const items = [{
name: "item1",
img: "img/pic/picture1.png"
},
name: "item2",
img: "img/pic/picture2.png"
},
name: "item3",
img: "img/pic/picture3.png"
}];
我从中获得一个随机的 img 属性。
const randomImg =items[Math.floor(Math.random() *items.length)].img;
itemImg.src = `${randomImg}`;
我想获取一个 name 属性并将其指定为 alt。你能指导我该怎么做吗?
我尝试了findIndex()方法和indexOf()。但仍然未定义或-1。
const altIndex = items.indexOf(randomImg);
itemImg.alt = items[altIndex].name;
//or
const altIndex = items.findIndex(ele => ele === randomImg[ele]);
我的方法正确吗?提前谢谢您,祝您有美好的一天!
你不能将随机项存储在变量中并使用它吗,例如,
randomItem
:
const items = [
{ name: "item1", img: "img/pic/picture1.png" },
{ name: "item2", img: "img/pic/picture2.png" },
{ name: "item3", img: "img/pic/picture3.png" }
];
const randomItem = items[Math.floor(Math.random() * items.length)];
console.log(`randomItem.name: ${randomItem.name}`);
console.log(`randomItem.img: ${randomItem.img}`);
// So you can do something like this now:
// itemImg.src = randomItem.img;
// itemImg.alt = randomItem.name;