简体   繁体   English

通过char javascript遍历字符串char

[英]traverse a string char by char javascript

function SimpleSymbols(str) { 
    var letter =['a','b','c','d','e','f','g','h','i','j',
    'k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];

    var newstr = "";
    for (var i = 0; i<str.length; i++){
        if (str.charAt(i).toLowerCase() in letter){
            newstr += "M";
        }
        else{
            newstr += "X";
        }
    }

return newstr; 

}

If str is "Argument goes here" it returns XXXXXXXXX. 如果str是“Argument goes here”,则返回XXXXXXXXX。 WHy doesn't it return MMMMMMMMMM? 为什么不返回MMMMMMMMMM?

you do not look up an entry in an array with in . 你别看了数组中的一个条目与in use indexOf() to find the position of an array entry. 使用indexOf()来查找数组条目的位置。 indexOf() will return the position or -1 if no entry is found. indexOf()将返回位置,如果未找到任何条目,则返回-1

for (var i = 0; i<str.length; i++){
    var strChar = str.charAt(i).toLowerCase();

    if ( letter.indexOf(strChar) >= 0 ) {
        newstr += "M";
    }
…

The in operator returns true if the object has a property with that name , not with that value . 如果对象具有具有该名称的属性,而不是该 ,则in运算符返回true

An array is basically an object with numeric properties. 数组基本上是具有数字属性的对象。 Ie the indexes are the property names of the object. 索引是对象的属性名称。 It basically looks like this: 它基本上看起来像这样:

var letters = {
  0: 'a',
  1: 'b',
  ...
  length: ...
};

So in your case the condition will only be true if str.charAt(i).toLowerCase() returns a number between 0 and letter.length (and since charAt only returns one character, it can only be 0-9 ). 所以你的情况的情况只会是true ,如果str.charAt(i).toLowerCase()返回之间的数字0letter.length (并且自charAt只返回一个字符,它只能是0-9 )。

Example: 例:

> var letters = ['a', 'b', 'c'];
> 'a' in letters // array doesn't have a property 'a'
false
> 0 in letters   // array has a property 0 (it's the first element)
true

So since, "Argument goes here" doesn't contain any digits, the in condition will always be false and that's why you get XXXXXX... as result. 因此, "Argument goes here"不包含任何数字, in条件将始终为false ,这就是为什么你得到XXXXXX...结果。

See the question " How do I check if an array includes an object in JavaScript? " for testing the existence of an element in an array. 请参阅问题“ 如何检查数组是否包含JavaScript中的对象? ”,以测试数组中是否存在元素。


FWIW, to make the in operator work, you would have to create an object of the form: FWIW,使得in操作者的工作,你就必须创建窗体的对象:

var letters = {
  'a': true,
  'b': true,
  // ...
};

but that's a bit cumbersome to write. 但写起来有点麻烦。

Allow me to offer a side view, another way handle what I think you intent to do by using Regular Expressions with something like: 请允许我提供侧视图,另一种方式是使用正则表达式处理我认为您打算做的事情:

"test2".replace(/[az]/gi,"M").replace(/[^M]/g,"X") //Outputs "MMMMX"

String.replace will replace an string that contains letters from [az] the i at the end of the expression means case insensitive. String.replace将替换包含来自[az]的字母的字符串,表达式末尾的i表示不区分大小写。 g means will search for all possible matches and not just the first match. g表示将搜索所有可能的匹配,而不仅仅是第一个匹配。 In the second expression [^M] this ^ means negation so anything that is not an M will be replaced with X . 在第二个表达式[^M]^意味着否定所以任何不是一个M将被替换X

There is another way in which we implement a custom function within the String.replace using Regular Expressions and it can be implemented like this: 还有另一种方法,我们使用正则表达式在String.replace实现自定义函数,它可以像这样实现:

"test2".replace(/([a-z])|([^a-z])/gi,
     function(m,g1, g2){ 
            return g1 ? "M" : "X";  
     });

In regular expression parenthesis creates groups and | 在正则表达式中,括号创建组和| means or in this expression ([az])|([^az]) there 2 groups one with letters from az and the other which means everything that is not az with the replace function we asked only for group g1 if it is group 1 is M otherwise is an X . 意味着或在这个表达式([az])|([^az])有2个组,一个字母来自az,另一个意味着所有不是az的替换函数我们只询问组g1如果它是组1是M否则是X

Another cool thing you could do is add this function to all your string by prototyping it like: 你可以做的另一个很酷的事情就是通过原型化将这个函数添加到你的所有字符串中:

String.prototype.traverse = function(){ return this.replace(/([a-z])|([^a-z])/gi,function(m,g1){ return g1 ? "M" : "X"  });}

Then it can be used as simple as: "test1".traverse(); 然后它可以像: "test1".traverse();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM