我已经能够将数组反转为一个字符串,但是无法将该字符串分配给指定长度的各个元素。我尝试过:
function ultimateReverse (array) {
let newArray = array.join("").split("");
let reversedArray = newArray.reverse();
return reversedArray.join("");
}
console.log(ultimateReverse(["I", "like", "big", "butts", "and", "I", "cannot", "lie!"]));
//!eiltonnacIdnasttubgibekilI
但是我们想要的结果是:
["!", "eilt", "onn", "acIdn", "ast", "t", "ubgibe", "kilI"]
因此,根据原始数组,第一个元素的长度应为1,第二个元素的长度应为4,第三个元素的长度应为3,依此类推...
是否可以将字符串拆分为元素数组,每个元素都有指定的长度?
我想通过执行以下操作从原始数组创建一个数组,该数组的长度由项目组成:
function ultimateReverse (array) {
let elementLengths = [];
let newArray = array.join("").split("");
let reversedArray = newArray.reverse().join("");
for (let i = 0; i < array.length; i++) {
let element = array[i];
elementLengths.push(element.length);
}
return reversedArray + " " + elementLengths;
}
console.log(ultimateReverse(["I", "like", "big", "butts", "and", "I", "cannot", "lie!"]));
//!eiltonnacIdnasttubgibekilI 1,4,3,5,3,1,6,4
现在,如果我可以根据原始元素的长度将字符串分成数组中的元素...
答案 0 :(得分:10)
首先构造完整的反向字符串,例如
!eiltonnacIdnasttubgibekilI
然后,从初始长度的数组(可以预先用.map
完成)中,遍历该数组,并从反转的字符串中重复slice
的长度,然后推入数组:
function ultimateReverse(array) {
const lengths = array.map(({ length }) => length);
let reversedStr = [...array.join("")].reverse().join('');
const result = [];
lengths.forEach((length) => {
result.push(reversedStr.slice(0, length));
reversedStr = reversedStr.slice(length);
});
return result;
}
console.log(ultimateReverse(["I", "like", "big", "butts", "and", "I", "cannot", "lie!"]));
您还可以将初始反向数据保留为splice
的数组,而不是重新分配reversedStr
:
function ultimateReverse(array) {
const lengths = array.map(({ length }) => length);
const reversedChars = [...array.join('')].reverse();
return lengths.map(
length => reversedChars.splice(0, length).join('')
);
}
console.log(ultimateReverse(["I", "like", "big", "butts", "and", "I", "cannot", "lie!"]));
答案 1 :(得分:1)
您还可以通过以下方式解决此问题:验证字符串,然后将其映射并使用substr
将其“切成碎片”,如下所示:
let reverse = arr => {
let i = 0, rData = [...arr.join('')].reverse().join('')
return arr.map(x => {
let str = rData.substr(i, x.length)
i += x.length
return str
})
}
console.log(reverse(["I", "like", "big", "butts", "and", "I", "cannot", "lie!"]))
基本上映射整个原始数组,并为组合后的反向字符串中的每个字符串substr
映射,与当前x长度一样多。