【问题标题】:Using an array of index values to access a part of an array in JSJS中使用索引值数组访问数组的一部分
【发布时间】:2021-08-08 15:49:27
【问题描述】:

我正在尝试找到一种方法来访问具有特定索引的数组的一部分,并且索引也在数组中。所以,我有类似的东西:

var arr = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven'];
var arrIndexes = [1, 3, 5];

我正在寻找一种简单的方法来使用arrIndexes 来访问arr 的这个特定部分,这样我的输出就只是['one', 'three', 'five']

【问题讨论】:

    标签: javascript arrays indexing


    【解决方案1】:

    您可以通过使用Array.prototype.map() 来减少计算量:

    var arr = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven'];
    var arrIndexes = [1, 3, 5];
    
    const res = arrIndexes.map(i=>arr[i])
    
    console.log(res);

    【讨论】:

    • 好答案!这是最优的 (y)
    • 谢谢!这很有帮助,我知道有一些我想不到的简单的事情:)
    【解决方案2】:

    您可以使用Array.prototype.filter()includes() 函数来实现。试试这个-

    var arr = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven'];
    var arrIndexes = [1, 3, 5];
    
    const res = arr.filter((item, index) => arrIndexes.includes(index));
    
    console.log(res);

    【讨论】:

      【解决方案3】:

      你可以像这样使用reduce函数

       let newAr=arr.reduce((prev,curr,idx,arr)=>{
          if(arrIndexes.includes(idx)){
              prev.push(arr[idx]);
          }
          return prev;
      },[])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-19
        • 2014-03-08
        • 2014-06-16
        • 1970-01-01
        • 1970-01-01
        • 2012-08-29
        • 1970-01-01
        • 2016-05-21
        相关资源
        最近更新 更多