我想提醒字符串的每个字母,但我不确定如何做到这一点。
如果我有:
var str = 'This is my string';
我希望能够分别提醒T h I s等等。这只是我正在研究的一个想法的开始,但我需要知道如何分别处理每个字母。
我在想,我可能需要在测试字符串的长度后使用分割函数。
我该怎么做呢?
我想提醒字符串的每个字母,但我不确定如何做到这一点。
如果我有:
var str = 'This is my string';
我希望能够分别提醒T h I s等等。这只是我正在研究的一个想法的开始,但我需要知道如何分别处理每个字母。
我在想,我可能需要在测试字符串的长度后使用分割函数。
我该怎么做呢?
当前回答
可能不止是解决了。只是想提供另一个简单的解决方案:
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);
});
其他回答
你可以简单地在数组中迭代它:
for(var i in txt){
console.log(txt[i]);
}
你可以试试这个
var arrValues = 'This is my string'.split('');
// Loop over each value in the array.
$.each(arrValues, function (intIndex, objValue) {
alert(objValue);
})
在今天的JavaScript中,你可以
Array.prototype.map。call('This is my string', (c) => c+c)
显然,c+c表示你想用c做的任何事情。
这将返回
[“TT”, “hh”, “ii”, “ss”, “”“, ”ii“, ”ss“, ”, “mm”, “yy”, “ ”ss“, ”tt“, ”rr“, ”ii“, ”nn“, ”gg“]
还有一个解决方案……
var strg= 'This is my string';
for(indx in strg){
alert(strg[indx]);
}
可以使用str. charat (index)或str[index]访问单个字符。但是后一种方式不是ECMAScript的一部分,所以你最好使用前一种方式。