【问题标题】:Access every other item in an array - JavaScript访问数组中的所有其他项目 - JavaScript
【发布时间】:2015-08-23 03:53:03
【问题描述】:

我是否可以访问数组中的所有其他项目?所以基本上,位置 0、2、4、6 等的所有项目。

如果有帮助,这是我的代码:

function pushToHash(key, value) {
    for (var t = 0; t < value.length; t++) {
    MQHash[key[t]] = value.slice(0, lineLength[t]);
    }
}

所以,我需要获取lineLength 的所有其他值。我只想要lineLength,而不是key。我正在考虑做一个模数,但不确定如何实现它。有什么想法吗?

提前致谢!

【问题讨论】:

    标签: javascript arrays


    【解决方案1】:

    这是一个函数,它将每 X 个元素(因子)截断一个数组。

    const truncateArray = (array: any[], factor: number): any[] => {
      let lastNumber = 0;
      return array.filter((element, index) => {
        const shouldIncludeThisElement = index === lastNumber + factor ? true : false;
        lastNumber = shouldIncludeThisElement ? index : lastNumber;
        return shouldIncludeThisElement;
      });
    };
    

    【讨论】:

      【解决方案2】:

      您可以像这样在数组过滤方法中使用索引(第二个参数):

      let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
      
      // filter out all elements that are located at an even index in the array.
      
      let x = arr.filter((element, index) => {
        return index % 2 === 0;
      })
      
      console.log(x) 
      // [1, 3, 5, 7, 9]
      

      【讨论】:

        【解决方案3】:

        如果您只想使用 lineLength 而不是 key,则添加第二个变量并在递增时使用 +=

        function pushToHash(key, value) {
            for (var t = 0, x = 0; t < value.length; t++, x += 2) {
                MQHash[key[t]] = value.slice(0, lineLength[x]);
            }
        }
        

        comma operator的力量...)

        【讨论】:

        • 完美!非常感谢!
        猜你喜欢
        • 2020-09-10
        • 1970-01-01
        • 2020-08-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多