javascript split(/\s+/).pop() - 它有什么作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18039052/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 10:33:54  来源:igfitidea点击:

split(/\s+/).pop() - what does it do?

javascriptregexsplit

提问by secr

Could you translate this expression to words?

你能把这个表达翻译成文字吗?

split(/\s+/).pop()

It is in javascript and uses regex to split a string, but what are the principles?

它在javascript中,使用regex来分割字符串,但是原理是什么?

回答by nnnnnn

That line of code will split a string on white space to create an array of words, and then return the last word.

那行代码将在空白处拆分一个字符串以创建一个单词数组,然后返回最后一个单词。

Presumably you have seen this used on a string of some kind, e.g.:

想必您已经在某种字符串上看到过这种用法,例如:

var someString = "Hello, how are you today?";
var lastWord = someString.split(/\s+/).pop();

In which case lastWordwould be "today?".

在这种情况下lastWord"today?"

If you did that one step at a time:

如果你一次做这一步:

var someString = "Hello, how are you today?";
var words = someString.split(/\s+/);

Now wordsis the array: ["Hello,", "how", "are", "you", "today?"]

现在words是数组:["Hello,", "how", "are", "you", "today?"]

Then:

然后:

var lastWord = words.pop();

Now lastWordis the last item from the array, i.e., "today?".

现在lastWord是数组中的最后一项,即"today?"

The .pop()methodalso actually removes the last item from the array (and returns it), so in my second example that would change wordsso that it would be ["Hello,", "how", "are", "you"].

.pop()方法实际上还从数组中删除了最后一项(并返回它),因此在我的第二个示例中words,它会更改为["Hello,", "how", "are", "you"].

If you do it all in one line as in my first example then you don't ever actually keep a reference to the array, you just keep the last item returned by .pop().

如果像我的第一个示例那样在一行中完成所有操作,那么您实际上永远不会保留对数组的引用,而只是保留由.pop().

MDN has more information about .split().

MDN 有更多关于.split().

Another way to get the last word from a string is as follows:

从字符串中获取最后一个单词的另一种方法如下:

var lastWord = someString.substr( someString.lastIndexOf(" ") + 1 );

回答by med116

TLDR:

域名注册地址:

1)the split part creates an array based on the regex /\s+/ (which means separate by whitespace)

1)拆分部分基于正则表达式 /\s+/ 创建一个数组(这意味着用空格分隔)

2) the pop part returns the last element of the array

2)pop部分返回数组的最后一个元素

could be rewritten as

可以改写为

var array = "one two three four five".split(/\s+/);
var lastMemberOfArray = array.pop()

I often use split(".").pop() to get file extension

我经常使用 split(".").pop() 来获取文件扩展名

var html = "holidays-and-parties/photos/a-pioneer-halloween.html"
var ext = html.split(".").pop(); // ext now holds 'html'