Javascript 在数组中的字符串中使用条件运算符(?True:False)

Javascript 在数组中的字符串中使用条件运算符(?True:False),javascript,arrays,string,substitution,conditional-operator,Javascript,Arrays,String,Substitution,Conditional Operator,我需要在数组中使用条件运算符,但它所引用的对象直到稍后才会创建 const guests = [ {id: 1, location: 86, name: "Handy", gender: 1}, {id: 2, location: 42, name: "Booby", gender: 2}, {id: 3, location: 42, name: "Ratty", gender: 1} ]; const guestD

我需要在数组中使用条件运算符,但它所引用的对象直到稍后才会创建


const guests = [
  {id: 1, location: 86, name: "Handy", gender: 1},
  {id: 2, location: 42, name: "Booby", gender: 2},
  {id: 3, location: 42, 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)]));
});
每位来宾的输出应如下所示:

“波比在这里。她在绕圈子,做倒立”

“老鼠来了。他坐在他最喜欢的椅子上,抚摸着自己”


在描述数组中,不能只使用
currentGuests.gender
,因为这是一个数组,而且还没有定义。这些职能需要:

const guestDescription1=(guest)=>[“坐在”+(guest.gender==1?“他的”:“她”)+
“最喜欢的椅子”、“站在火炉旁”、“绕圈行走”];
const guestdescription 2=(guest)=>[“大声唱歌”、“倒立”,
“触摸”+(guest.gender==1?“他”:“她”+“自我”];
然后你可以用guest参数正常调用它:

guestDescription1(currentGuests[key])[Math.floor(Math.random()*3]

正如您所观察到的,这不起作用,因为您在给它赋值之前正在使用
currentGuests
。由于
currentGuests
只依赖于
guests
,您只需将
currentGuests
的定义移到
guests
的定义之后。听起来您真正想要的是定义一个函数,稍后可以将随后创建的列表中的一个来宾传递给该函数