繁体   English   中英

根据另一个属性设置嵌套对象属性

[英]set nested object properties based on another property

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

这是到目前为止我的代码的快照:

//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
            }
        }
    }
}

我想遍历所有字符以根据regExp设置matches值,并根据matches长度设置count值。

这个问题的最高答案是我最近解决我的问题的方式。 访问/处理(嵌套的)对象,数组或JSON

您应该对代码进行几处更改:

  1. 不需要检查: for in循环中的if (characters.hasOwnProperty(key))
  2. 您不能使用点符号访问变量属性: var obj = characters.key; 应该是var obj = characters[key];
  3. 同样,无需检查: if (obj.hasOwnProperty(prop))
  4. 如果要操纵字符对象属性,则需要访问对象的属性,而不仅仅是键入键名。

纠正这些问题(主要是#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."
] 

暂无
暂无

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

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