【问题标题】:Splicing string values using functions and loops and storing as an array使用函数和循环拼接字符串值并存储为数组
【发布时间】:2019-01-25 08:54:49
【问题描述】:

我有一个数字列表,它是一个使用循环的字符串值我想将此字符串拆分为数组中的不同变量,第一个长度为 3,长度为 6,长度为 7,最后一个长度为 3。如何这可以使用函数和循环来完成。

【问题讨论】:

  • 字符串的长度是固定的吗?

标签: javascript arrays string loops substring


【解决方案1】:

您可以映射子字符串。

var str = '000111111122222223333333444444455555556666666mmmm',
    lengths = [3, 7, 7, 7, 7, 7, 7, 3],
    result = lengths.map((i => l => str.slice(i, i += l))(0));

console.log(result);

【讨论】:

  • 这段代码中的 l 是什么意思,当你说 i => l 我不明白这是如何工作的,因为你没有定义 l。提前致谢
  • (i => l => str.slice(i, i += l))(0) 是一个 IIFE,在 i 上有一个闭包,其值为 0,它返回一个函数作为 l => str.slice(i, i += l) 的回调函数,其中 l 采用单个长度并将其相加到i 作为子字符串。
【解决方案2】:

我们可以这样做:

 
let str = '000111111122222223333333444444455555556666666mmmm';

// Defines the lengths we're using
let lengths = [3,7,7,7,7,7,7,3];

let index = 0;

let result = lengths.reduce((acc,n) => {
    acc.push(str.slice(index, index += n));
    return acc;
} , [])

console.log(result);

【讨论】:

    【解决方案3】:

    一个通用的方法是,如果你想在一个变量中你可以使用 subStringLengthMaps 键,:-

    let str="abcdefghijklmnopqrstu";
    let  subStringLengthMap={a:3, b:7, c:7 , d:3};
    
    //making pure funciton
    var getStrings = function(str, subStringLengthMap){
      let result =[];
      Object.keys(subStringLengthMap).forEach(function(key){
      let temp = str.slice(0, subStringLengthMap[key]);
      result.push(temp);
        str = str.replace(temp,'');
      })
    
      return result;
    
    }
    
    //call the function
    console.log(getStrings(str, subStringLengthMap))
    

    【讨论】:

      【解决方案4】:

      这是一种方法:

      let theArray = document.getElementById('theArray');
      let theVariable = document.getElementById('theVariable');
      let targetString = "122333444455555666666";
      let dataSizes = [1, 2, 3, 4, 5, 6];
      var result = [];
      var pos = 0;
      dataSizes.forEach( (size) => {
          result.push(targetString.substr(pos, size));
          pos += size;
      });
      theArray.textContent = result.toString();
      let [one, two, three, four, five, six] = result;
      theVariables.textContent = `${one}-${two}-${three}-${four}-${five}-${six}`;
      

      【讨论】:

        猜你喜欢
        • 2012-09-16
        • 2012-08-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-02
        • 1970-01-01
        • 2018-03-04
        • 2013-07-04
        相关资源
        最近更新 更多