提取字符串中每个其他单词的算法? [英] Algorithm to take out every other word in a string?

查看:74
本文介绍了提取字符串中每个其他单词的算法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Javascript中,如果我有这样的字符串:你好,很高兴认识你
我想还给我的是奇怪的地方,所以我会得到:你好

In Javascript, if I have a string like so: "Hello nice to meet you" And what I would like returned to me are the words in odd places so I would get: "Hello to you"

我如何为此编写代码?

推荐答案

您可以使用 过滤器 创建一个新数组,其中的元素具有偶数索引。

You can use filter to create a new array with elements that have an even index.

只需记住,奇数位置的单词实际上位于偶数索引,因为javascript中的数组是零索引的。

Just remember that the words in "odd" places are actually located at even indexes, since arrays in javascript are zero-indexed.

var s = 'Hello nice to meet you'

var evenWords = (s) => s.split(' ').filter((element, index) => index % 2 === 0).join(' ');

console.log(evenWords(s))

这篇关于提取字符串中每个其他单词的算法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆