I have a list of numbers that is a string value using a loop I want to split this string into different variables in an array, the first of length 3 and the 6 of length 7 and the last of length 3. How can this be done using functions and loops.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
We could do something like this:
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);
回答2:
You could map the sub strings.
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);
回答3:
Here's one way to do that:
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}`;
回答4:
a generic way of doing this will be, if you want in a variable you can use subStringLengthMaps key, :-
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))