【问题标题】:Javascript Map Array Last ItemJavascript 映射数组最后一项
【发布时间】:2016-11-05 16:36:43
【问题描述】:

我有这个:

map = ranks.map((row, r) => (
  row.map((rank, i) => {
    return [element(r, i, state, rank, toggled, onClick)];
  })
));

它通过一个二维数组映射。 在每一行之后,我想插入<div class="clearfix"></div>

我想,如果我能以某种方式获取每一行的最后一个索引,那么我将能够在行映射回调中使用它。谁能告诉我怎么做?

【问题讨论】:

    标签: javascript arrays multidimensional-array


    【解决方案1】:

    尝试类似:

    row.map((rank, i, row) => {
      if (i + 1 === row.length) {
        // Last one.
      } else {
        // Not last one.
      }
    })
    

    旧答案:

    const rowLen = row.length;
    row.map((rank, i) => {
      if (rowLen === i + 1) {
        // last one
      } else {
        // not last one
      }
    })
    

    【讨论】:

      【解决方案2】:

      更短的方法是使用 .map 结合三元运算符,像这样。

      const positions = ["first", "second", "third", "fourth"]
      
      positions.map((x, index, array) => {
          index === array.length -1 
              ? console.log("this is the last item in the array")
               : console.log( x)
      }
      

      ///////////解释

      x ### 返回当前元素 .map 正在循环遍历

      index ### 返回当前元素的索引(数组中项的位置)。

      array ### 返回我们正在循环的相同元素,所以如果我们像这样使用 sth

       ["first", "second", "third", "fourth"].map...
      

      我们仍然会得到我们正在循环的数组

      array.length - 1 ### 给出了数组的长度, - 1 给出了数组中最后一个元素的索引。

      【讨论】:

        【解决方案3】:

        更少的代码行得到相同的结果

        row.map((rank, i, {length}) => (
        
          //last element
          if(i + 1 === length){ 
        
          }
        ));
        

        【讨论】:

        • 这是最好的解决方案!
        【解决方案4】:

        正如 LeoYuan 所回答的,这是正确的答案,但可以稍微改进一下。
        map 接受带有第三个参数的函数,即迭代数组本身。

        row.map((rank, i, arr) => {
            if (arr.length - 1 === i) {
                // last one
            } else {
                // not last one
            }
        });
        

        或者更短的版本,使用对象解构(感谢 cmets 的 Jose):

        row.map((rank, i, {length}) => {
            if (length - 1 === i) {
                // last one
            } else {
                // not last one
            }
        });
        

        使用arr.length 代替row.length 是一种更好且正确的方法,原因如下:

        1. 当您混合范围时,可能会导致意外错误,尤其是在编写不佳或设计不佳的代码中。一般来说,尽可能避免在作用域之间混用总是一种好方法。

        2. 当您想提供一个显式数组时,它也可以工作。例如

          [1,2,3,4].map((rank, i, arr) => {
              if (arr.length - 1 === i) {
                  // last one
              } else {
                  // not last one
              }
          });
          
        3. 如果你想将回调移动到map 范围之外(主要是为了更好的性能),使用row.length 是错误的,因为它超出了范围。例如。在 OP 案例中:

          const mapElement = (rowIndex, state, toggled, onClick) => {
              return (rank, i, arr) => {
                  let lastIndex = arr.length - 1;
                  return [element(rowIndex, i, state, rank, toggled, onClick, lastIndex)];
              };
          };
          
          map = ranks.map((row, r) => row.map(mapElement(r, state, toggled, onClick)));
          

        【讨论】:

        • 为什么要加arr而不是row.length
        • @Sanderfish 三个原因: 1. 一般来说,我不喜欢混合作用域,这样可以使它更清晰的解决方案,尤其是当这段代码是大型应用程序的一部分时; 2. 此解决方案也适用于明确定义的数组,例如[1,2,3].map((rank, i, arr) => { ... }); 3. 如果出于某种原因(例如在循环中)您决定将回调移到范围之外,那么执行row.length 将根本不起作用。我将更新我的答案以使其清楚。
        • 你也可以.map((rank, i, { length }) => { ... })
        • 同意你的方法更好
        • 如果我错了,请纠正我,但对于 React JSX 来说,这似乎也是更好的方法,因为你不能只声明一个内联变量?
        【解决方案5】:

        也许访问array.map() 中的length 属性的最简洁的方法(虽然有点“脏”——你可能会遇到一些 ESLint 错误,TypeScript 也可能对此不满意)是把它拉出来(通过解构)第三个回调参数(这是我们正在映射的数组),然后分配一个新属性 e。 G。 lastIndex,哪个值是从之前拉出的length推导出来的:

        let list = ["Alice", "Bob", "Cedrick", "David", "Emily"]
        
        let mapped = list.map((item, i, {length, lastIndex = length - 1}) => {
          return i === lastIndex ? "lastitem: " + item : item
        })
        
        console.log(mapped)

        【讨论】:

          【解决方案6】:

          简化上面的答案

          const array = ['apple','orange','banana'];
          
          array.map((element, index) => (index === array.length - 1) ? \`${element}.\` : \`${element},\`);
          

          【讨论】:

            【解决方案7】:
            const array = ['apple','orange','banana'];
            
            array.map((element, index) => {
              //Last element
              if (index === array.length - 1) {
                return `${element}.`;
              }
              //Another elements
              return `${element}, `;
            })}
            

            将返回apple, orange, banana.

            【讨论】:

              【解决方案8】:

              您可以使用数组的长度检查最后一个索引。这是一个逻辑

              var randomnumber = Math.floor(Math.random() * (100 - 10 + 1)) + 10
              
              console.log("your last index is dynamic, ehich is ",randomnumber-1);
              let arry = [];
              for (i=1;i<randomnumber;i++){
                  arry.push(i)
              }
              
                  arry.map((data,index)=>{
                        if(index == arry.length-1 ){
                          console.log("last index data  ",data)
                        }
                        else{
                        console.log("remain data ",data)
                        
                        }
              
                  })
              
                  console.log("your last index is dynamic, which is ",randomnumber-1);
              这也适用于动态数组变化.. 这是我使用的一种过于简单的技术.. :-)

              【讨论】:

              • 我发现这是一个最佳解决方案。谢谢你的朋友。
              【解决方案9】:

              对已接受的答案略有改进:

              const lastIndex = row.length - 1;
              row.map((rank, i) => {
                if (i === lastIndex) {
                  // last one
                } else {
                  // not last one
                }
              })
              

              这会从循环内部删除算术。

              【讨论】:

              • 如果数组的长度在运行时动态变化(大多数情况下都会发生),这将不起作用。这就是为什么您必须每次都检查数组的长度。请注意,row.length 不会降低性能,因为它不会在您每次请求时计算项目,而是将长度作为参数存储在 Array 实例中。
              猜你喜欢
              • 1970-01-01
              • 2019-12-10
              • 1970-01-01
              • 1970-01-01
              • 2021-08-18
              • 1970-01-01
              • 2018-08-06
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多