【问题标题】:JavaScript prototype: filter->if(which function?)->mapJavaScript 原型:filter->if(which function?)->map
【发布时间】:2023-01-17 11:42:39
【问题描述】:

我正在研究反应。我正在努力使用 JavaScript 原型。我想做的是下面。

  1. 如果键入searchWord,则将数组(props.rows) 过滤为包含该词的数组。
  2. 如果元素个数大于rowsPerPage,则只显示rowsPerPage

    但是,我输入的内容却像这样反向工作。 对rowsPerPage中的元素进行切片,然后过滤包含searchWord的元素。

    我不知道需要哪个功能。请帮我。先感谢您。

    (如果可以仅使用原型编写代码,我想这样做。)

    (+ 我编辑了代码来修剪它。)

    // reversed sequence
    {(rowsPerPage > 0
    ? props.rows.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
    : props.rows
    )
    .filter((row) =>
    !searchWord.length || row.name
      .toString()
      .includes(searchWord.toString()) 
    )
    .map((item) => (
      <Hello />
    ))}
    
    // what I tried
    {props.rows
    .filter((row) =>
      !searchWord.length || row.name
        .toString()
        .includes(searchWord.toString()) 
    )
    ?????.((?????) => (
      rowsPerPage > 0
      ? ?????.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
      : ?????
    ))
    .map((item) => (
      <Hello />
    ))}
    

【问题讨论】:

标签: javascript reactjs arrays prototype


【解决方案1】:

尝试将其移动到变量

let filteredRows = props.rows
  .filter((row) =>
    !searchWord.length || row.name
      .toString()
      .toLowerCase()
      .includes(searchWord.toString().toLowerCase()) 
  );

if (rowsPerPage > 0) {
  filteredRows = filteredRows.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
}


return filteredRows.map(item => (
  <TableRow key={item.id} hover>
    <TableCell component="th" scope="row">
      {item.id}
    </TableCell>
    <TableCell>
      {item.name}
    </TableCell>
  </TableRow>
))

或不推荐的方法

{props.rows
.filter((row) =>
  !searchWord.length || row.name
    .toString()
    .toLowerCase()
    .includes(searchWord.toString().toLowerCase()) 
)
.slice(...(rowsPerPage > 0 ? [page * rowsPerPage, page * rowsPerPage + rowsPerPage] : []))
.map((item) => (
  <TableRow key={item.id} hover>
    <TableCell component="th" scope="row">
      {item.id}
    </TableCell>
    <TableCell>
      {item.name}
    </TableCell>
  </TableRow>
))}

【讨论】:

  • 感谢您的分享。只用原型写代码是不可能的?
  • 你是说像链条吗?我已经编辑了我的答案。
  • 谢谢你,问题解决了!!!
猜你喜欢
  • 2021-12-19
  • 2022-12-02
  • 1970-01-01
  • 2017-11-05
  • 2016-05-17
  • 2019-06-14
  • 1970-01-01
  • 1970-01-01
  • 2016-12-26
相关资源
最近更新 更多