基于另一个属性设置嵌套对象属性

时间:2014-03-06 18:51:44

标签: javascript regex loops object properties

我想计算文字中出现的字符数,然后显示每个字符的总数。我的主要问题是第一部分。

以下是我的代码的快照:

//define text and characters to be searched for
var theArticle = document.getElementById('theText'),
    docFrag = document.createDocumentFragment(),
    theText = theArticle.innerText,
    characters = {
    a: {
        regExp: /a/g,
        matches: [],
        count: 0
    },
    b: {
        regExp: /b/g,
        matches: [],
        count: 0
    },
    c: {
        regExp: /c/g,
        matches: [],
        count: 0
    }

    etc…
}

for (var key in characters) {
    if (characters.hasOwnProperty(key)) {
        var obj = characters.key;
        for (var prop in obj) {
            if (obj.hasOwnProperty(prop)) {
                matches = theText.match(regExp); // pretty sure my problem is here
                count = matches.length; // and here
            }
        }
    }
}

我想循环遍历所有字符,根据matches设置regExp的值,并根据count的长度设置matches的值。< / p>

这个问题的最佳答案是我最接近解决我的问题。 Access / process (nested) objects, arrays or JSON

1 个答案:

答案 0 :(得分:0)

应该对您的代码进行一些更改:

  1. 您的if (characters.hasOwnProperty(key))循环内无需检查:for in
  2. 您无法使用点表示法访问变量属性:var obj = characters.key;应为var obj = characters[key];
  3. 同样,不需要检查:if (obj.hasOwnProperty(prop))
  4. 如果您正在尝试操作角色对象属性,则需要访问对象上的属性,而不仅仅是键入键名称。
  5. 纠正这些事情(主要是#2),它应该按预期工作。

    但是,我会完全重新调整您的功能实现:

    我首先要简单地定义一个字符串数组:

    var characters = ['a','b','c','asd'];
    

    然后编写一个通用函数来处理您的功能:

    function findCharsInString(array, string) {
        // map a "results" function to each character in the array
        return array.map(function(c) {
            // make a check to ensure we're working with a string that is only one character
            if (typeof c === 'string' && c.length === 1) {
                // create a RegExp from each valid array element
                var matches = string.match(RegExp(c, 'g'));
                // return an anonymous results object for each character
                return {
                    matches: matches,
                    count: matches.length
                };
            } else { // if there is an invalid element in the array return something
                return 'Invalid array element.';
            }
        });
    }
    

    并将其应用于您的characters数组和theText字符串:

    var theText = 'asjdbasccshaskjhsa';
    console.log(findCharsInString(characters, theText));
    

    日志:

    [
        {
            matches:
                ["a","a","a","a"],
            count:
                4
        },
        {
            matches:
                ["b"],
            count:
                1
        },
        {
            matches:
                ["c","c"],
            count:
                2
        },
        "Invalid array element."
    ]