使用函数和循环拼接字符串值并存储为数组

时间:2018-08-18 15:42:23

标签: javascript arrays string loops substring

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

this is the simple way I've done it, however I want to achieve the same outcome but using loops

4 个答案:

答案 0 :(得分:1)

我们可以做这样的事情:

 
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);

答案 1 :(得分: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);

答案 2 :(得分:0)

这是一种方法:

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}`;

答案 3 :(得分:0)

一种通用的方法是,如果您想要一个变量,则可以使用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))