如何解决在数组内的字符串中使用条件运算符 (?True:False)
我需要在数组中使用条件运算符,但它所指的对象直到稍后才创建。
const guests = [
{id: 1,location: 86,name: "Handy",gender: 1},{id: 2,location: 42,name: "Booby",gender: 2},{id: 3,name: "Ratty",gender: 1}
];
const guestDescription1 = ["sitting in" + (currentGuests.gender === 1?"his":"her") +
" favorite chair","standing by the fire","walking in circles"];
const guestDescription2 = ["singing loudly","doing handstands","touching" + (currentGuests.gender === 1?"him":"her") + "self"];
...
var currentGuests = guests.filter(guest => guest.location === 42);
Object.keys(currentGuests).forEach(key => {
console.log(currentGuests[key].name + " is here.");
console.log((currentGuests[key].gender === 1?"He":"She") + " is "
+ (guestDescription1[Math.floor(Math.random() * 3)]) + " and "
+ (guestDescription2[Math.floor(Math.random() * 3)]));
});
每位出席的客人的输出应该是这样的:
“Booby 来了。她在转圈和倒立”
“Ratty 来了。他坐在他最喜欢的椅子上,抚摸着自己”
https://jsfiddle.net/nso6wg2c/
解决方法
在描述数组中,您不能只使用 currentGuests.gender
,因为它是一个数组,而且还没有定义。那些必须是函数:
const guestDescription1 = (guest) => ["sitting in " + (guest.gender === 1?"his":"her") +
" favorite chair","standing by the fire","walking in circles"];
const guestDescription2 = (guest) => ["singing loudly","doing handstands","touching " + (guest.gender === 1?"him":"her") + "self"];
然后你可以用guest param正常调用它:
guestDescription1(currentGuests[key])[Math.floor(Math.random() * 3)]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。