gpt4 book ai didi

javascript - 反转数组,让新数组中的元素与原始数组元素的长度相等 - JavaScript

转载 作者:可可西里 更新时间:2023-11-01 02:23:03 28 4
gpt4 key购买 nike

试图解决this kata on Codewars .

我已经能够将数组反转为字符串,但无法将此字符串分配给指定长度的单个元素。我试过:

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

现在,如果我可以根据原始元素的长度将字符串拆分为数组中的元素...

最佳答案

首先构建完整的反转字符串,例如

!eiltonnacIdnasttubgibekilI

然后,从一个初始长度的数组(可以提前使用 .map 完成)迭代该数组,并从反向数组中切片该长度字符串,并推送到一个数组:

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!"]));

您还可以将初始反转数据保留为您拼接的数组,而不是重新分配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!"]));

关于javascript - 反转数组,让新数组中的元素与原始数组元素的长度相等 - JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56204534/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com