首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >根据另一个数组的奇数索引和偶数索引元素创建数组

根据另一个数组的奇数索引和偶数索引元素创建数组
EN

Stack Overflow用户
提问于 2019-08-06 19:03:14
回答 5查看 64关注 0票数 2

我想用两个数组(sentenceslinks )填充、奇数索引和偶数索引,即sentence数组的

以下是我尝试但没有成功的地方:

代码语言:javascript
运行
复制
     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)

预期产出应是:

代码语言:javascript
运行
复制
//let links = ["60-1", "6-2", "16-32"];
//let sentences = ["don't you worry", "I gonna make sure that", "tommorow is  another great day"];
EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2019-08-06 19:13:27

您可以匹配部分,并省略空字符串的分裂。

代码语言:javascript
运行
复制
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);
代码语言:javascript
运行
复制
.as-console-wrapper { max-height: 100% !important; top: 0; }

票数 4
EN

Stack Overflow用户

发布于 2019-08-06 19:07:07

您的初始尝试是接近的,如果您稍微修改for循环,您就可以实现您想要的结果。

代码语言:javascript
运行
复制
// 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]);
    }
}
票数 2
EN

Stack Overflow用户

发布于 2019-08-06 19:14:07

下面是一个使用Array.prototype.reduce的简单解决方案

代码语言:javascript
运行
复制
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);

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57382452

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档