如何使用 Javascript 处理文本的每个字母?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1966476/
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-08-22 22:09:01  来源:igfitidea点击:

How can I process each letter of text using Javascript?

javascriptjquerystring

提问by Nic Hubbard

I would like to alert each individual letter of a string, but I am unsure how to do this.

我想提醒字符串的每个字母,但我不确定如何执行此操作。

So, if I have:

所以,如果我有:

var str = 'This is my string';

I would like to be able to separately alert T, h, i, s, etc. This is just the beginning of an idea that I am working on, but I need to know how to process each letter separately.

我希望能够分别提醒 T、h、i、s 等。这只是我正在研究的一个想法的开始,但我需要知道如何分别处理每个字母。

I want to use jQuery and was thinking I might need to use the split function after testing what the length of the string is.

我想使用 jQuery,并认为在测试字符串的长度后我可能需要使用 split 函数。

Ideas?

想法?

回答by Eli Grey

If the order of alerts matters, use this:

如果警报的顺序很重要,请使用以下命令:

for (var i = 0; i < str.length; i++) {
  alert(str.charAt(i));
}

If the order of alerts doesn't matter, use this:

如果警报的顺序无关紧要,请使用以下命令:

var i = str.length;
while (i--) {
  alert(str.charAt(i));
}

var str = 'This is my string';

function matters() {
  for (var i = 0; i < str.length; i++) {
    alert(str.charAt(i));
  }
}

function dontmatter() {
  var i = str.length;
  while (i--) {
    alert(str.charAt(i));
  }
}
<p>If the order of alerts matters, use <a href="#" onclick="matters()">this</a>.</p>

<p>If the order of alerts doesn't matter, use <a href="#" onclick="dontmatter()">this</a>.</p>

回答by Mr. Goferito

It's probably more than solved. Just want to contribute with another simple solution:

这可能不仅仅是解决了。只想提供另一个简单的解决方案:

var text = 'uololooo';

// With ES6
[...text].forEach(c => console.log(c))

// With the `of` operator
for (const c of text) {
    console.log(c)
}

// With ES5
for (var x = 0, c=''; c = text.charAt(x); x++) { 
    console.log(c); 
}

// ES5 without the for loop:
text.split('').forEach(function(c) {
    console.log(c);
});

回答by miku

One possible solution in pure javascript:

纯 javascript 中的一种可能解决方案:

for (var x = 0; x < str.length; x++)
{
    var c = str.charAt(x);
    alert(c);
}

回答by zurfyx

How to process each letter of text (with benchmarks)

如何处理文本的每个字母(带基准)

https://jsperf.com/str-for-in-of-foreach-map-2

https://jsperf.com/str-for-in-of-foreach-map-2

for

为了

Classicand by far the one with the most performance. You should go with this one if you are planning to use it in a performance critical algorithm, or that it requires the maximum compatibility with browser versions.

经典,迄今为止性能最高的一款。如果您打算在性能关键算法中使用它,或者它需要与浏览器版本的最大兼容性,则应该使用它。

for (var i = 0; i < str.length; i++) {
  console.info(str[i]);
}

for...of

对于...的

for...ofis the new ES6for iterator. Supported by most modern browsers. It is visually more appealing and is less prone to typing mistakes. If you are going for this one in a production application, you should be probably using a transpiler like Babel.

for...of是新的ES6迭代器。大多数现代浏览器都支持。它在视觉上更具吸引力,并且不太容易出现打字错误。如果您打算在生产应用程序中使用这个,您可能应该使用像Babel这样的转译器。

let result = '';
for (let letter of str) {
  result += letter;
}

forEach

为每个

Functionalapproach. Airbnb approved. The biggest downside of doing it this way is the split(), that creates a new array to store each individual letter of the string.

功能方法。Airbnb 批准。这样做的最大缺点是split(), 它会创建一个新数组来存储字符串的每个字母。

Why? This enforces our immutable rule. Dealing with pure functions that return values is easier to reason about than side effects.

为什么?这强制执行我们的不可变规则。处理返回值的纯函数比副作用更容易推理。

// ES6 version.
let result = '';
str.split('').forEach(letter => {
  result += letter;
});

or

或者

var result = '';
str.split('').forEach(function(letter) {
  result += letter;
});


The following are the ones I dislike.

以下是我不喜欢的。

for...in

因为...在

Unlike for...of, you get the letter index instead of the letter. It performs pretty badly.

与 for...of 不同,您得到的是字母索引而不是字母。它的表现非常糟糕。

var result = '';
for (var letterIndex in str) {
  result += str[letterIndex];
}

map

地图

Function approach, which is good. However, map isn't meant to be used for that. It should be used when needing to change the values inside an array, which is not the case.

函数方法,这很好。但是,地图并不打算用于此目的。当需要更改数组内的值时应该使用它,但事实并非如此。

// ES6 version.
var result = '';
str.split('').map(letter => {
  result += letter;
});

or

或者

let result = '';
str.split('').map(function(letter) {
  result += letter;
});

回答by hippietrail

Most if not all of the answers here are wrong because they will break whenever there is a character in the string outside the Unicode BMP (Basic Multilingual Plane). That means all Emoji will be broken.

这里的大多数(如果不是全部)答案都是错误的,因为只要字符串中有 Unicode BMP (Basic Multilingual Plane) 之外的字符,它们就会中断。这意味着所有表情符号都将被破坏

JavaScript uses UTF-16Unicode for all strings. In UTF-16, characters beyond the BMP are made out of two parts, called a "SurrogatePair" and most of the answers here will process each part of such pairs individually instead of as a single character.

JavaScript对所有字符串使用UTF- 16Unicode。在 UTF-16 中,超出 BMP 的字符由两部分组成,称为“代理”,此处的大多数答案将单独处理此类对的每个部分,而不是将其作为单个字符处理。

One way in modern JavaScript since at least 2016 is to use the new String iterator. Here's the example (almost) straight out of MDN:

至少从 2016 年开始,现代 JavaScript 中的一种方法是使用新的String iterator。这是(几乎)直接来自 MDN 的示例:

var string = 'A\uD835\uDC68B\uD835\uDC69C\uD835\uDC6A';

for (var v of string) {
  alert(v);
}
// "A"
// "\uD835\uDC68"
// "B"
// "\uD835\uDC69"
// "C"
// "\uD835\uDC6A"

回答by Adriaan Stander

You can try this

你可以试试这个

var arrValues = 'This is my string'.split('');
// Loop over each value in the array.
$.each(arrValues, function (intIndex, objValue) {
    alert(objValue);
})

回答by Pamsix

One more solution...

另一种解决方案...

var strg= 'This is my string';
for(indx in strg){
  alert(strg[indx]);
}

回答by Downgoat

When I need to write short code or a one-liner, I use this "hack":

当我需要编写短代码或单行代码时,我使用这个“hack”:

'Hello World'.replace(/./g, function (char) {
    alert(char);
    return char; // this is optional 
});

This won't count newlines so that can be a good thing or a bad thing. If you which to include newlines, replace: /./with /[\S\s]/. The other one-liners you may see probably use .split()which has many problems

这不会计算换行符,因此这可能是一件好事或一件坏事。如果您要包含换行符,请将: 替换/.//[\S\s]/。您可能看到的其他单线可能会使用.split(),但存在很多问题

回答by papajson

New JS allows this:

新的 JS 允许这样做:

const str = 'This is my string';
Array.from(str).forEach(alert);

回答by Martin Wantke

It is better to use the for...of statement, if the string contains unicode characters, because of the different byte size.

如果字符串包含 unicode 字符,最好使用 for...of 语句,因为字节大小不同。

for(var c of "tree ľ") { console.log(c); }
//"A".length === 3