我想用两个数组(sentences
和links
)填充、奇数索引和偶数索引,即sentence
数组的:
以下是我尝试但没有成功的地方:
let link_sentence = ">60-1> don't you worry >6-2> I gonna make sure that >16-32> tomorrow is another great day"; //
let sentence = link_sentence.split(">")
let sentences= []
let links = []
for(let i = 0; i < sentence.length; i += 2) {
sentences.push(sentence[i]);
}
console.log(sentences)
预期产出应是:
//let links = ["60-1", "6-2", "16-32"];
//let sentences = ["don't you worry", "I gonna make sure that", "tommorow is another great day"];
发布于 2019-08-06 19:13:27
您可以匹配部分,并省略空字符串的分裂。
var link_sentence = ">60-1> don't you worry >6-2> I gonna make sure that >16-32> tomorrow is another great day",
sentences = [],
links = [];
link_sentence
.match(/\>[^>]+/g)
.reduce(
(r, s, i) => (r[i % 2].push(s.slice(1)), r),
[links, sentences]
);
console.log(sentences);
console.log(links);
.as-console-wrapper { max-height: 100% !important; top: 0; }
发布于 2019-08-06 19:07:07
您的初始尝试是接近的,如果您稍微修改for
循环,您就可以实现您想要的结果。
// remove first value from the array if the value is empty
if (!sentence[0]) {
sentence.shift();
}
for(let i = 0; i < sentence.length; i++) {
if (i % 2 === 0) {
links.push(sentence[i]);
} else {
sentences.push(sentence[i]);
}
}
发布于 2019-08-06 19:14:07
下面是一个使用Array.prototype.reduce
的简单解决方案
const sentence = ">60-1> don't you worry >6-2> I gonna make sure that >16-32> tomorrow is another great day".split(">")
const {links, sentences} = sentence.reduce((acc, val, index) => {
acc[index % 2 === 0 ? 'links' : 'sentences'].push(val);
return acc;
}, {
links: [],
sentences: []
});
console.log(links, sentences);
https://stackoverflow.com/questions/57382452
复制相似问题