为了账号安全,请及时绑定邮箱和手机立即绑定

通过 findIndex 按索引查找对象,如果没有找到则返回第一项

通过 findIndex 按索引查找对象,如果没有找到则返回第一项

小唯快跑啊 2023-01-06 16:22:07
该函数findIndex将返回元素的索引,如果在列表中找到,则返回-1但是,如果什么都没有找到,我想要一个现有的固定项,即第一个,而不是检查返回值:if (id === -1)  id = 0;在 JavaScript 中有没有简单或更短的方法?var items = [{  message: 'Hello World',  day: 'j1'}, {  message: 'Lorem ipsum dolor sit',  day: 'j2'}]function idbyDay(day) {  return this.items.findIndex(q => q.day === day);}function myFunction() {    var day = document.getElementById("day").value  console.log(day);  var id = this.idbyDay(day);  if (id === -1)    id = 0;  console.log(this.items[id]);}<input id="day" value="no"><button onclick="myFunction()">Try it</button>
查看完整描述

1 回答

?
一只甜甜圈

TA贡献1836条经验 获得超5个赞

您可以使用三元运算符,但不能再简化它了。


function idbyDay(day) {

  const idx = this.items.findIndex(q => q.day === day)

  return idx !== -1 ? idx : 0;

}

或者,由于您仅使用索引从数组中获取项目,因此您可以使用Array#findnullish 合并运算符来提供默认值。


function itembyDay(day) {

  return this.items.find(q => q.day === day) ?? this.items[0];

}


查看完整回答
反对 回复 2023-01-06
  • 1 回答
  • 0 关注
  • 293 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信