获取数组中字符串的最后一个元素(JavaScript)

时间:2018-11-08 16:26:44

标签: javascript arrays string

示例:

var someArray = ["My Name is", "My is Name", "Name my is", "is Name my"]

我想打印每个字符串的最后一个元素,所以:

output: is, Name, is, my

我不知道我应该从哪里开始。我首先想到的是拆分数组并打印最后一个索引,但我没有成功

3 个答案:

答案 0 :(得分:2)

使用Array.map

var someArray = ["My Name is", "My is Name", "Name my is", "is Name my"];
let result = someArray.map(v => {
  let temp = v.split(" ");
  return temp[temp.length-1];
})
console.log(result);

答案 1 :(得分:2)

您可以使用regular expression来匹配最后一个单词。

var someArray = ["My Name is", "My is Name", "Name my is", "is Name my"]
var result = someArray.map(item => item.match(/\w+$/)[0]);
console.log(result);

答案 2 :(得分:1)

var someArray = ["My Name is", "My is Name", "Name my is", "is Name my"];
var lastElements = "";

someArray.forEach(str => {
  splitStr = str.split(" ");
  lastElements += splitStr[splitStr.length - 1] + ", ";
});

console.log('output: ', lastElements);

//Outputs output:  is, Name, is, my,