我想计算文字中出现的字符数,然后显示每个字符的总数。我的主要问题是第一部分。
以下是我的代码的快照:
//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
答案 0 :(得分:0)
应该对您的代码进行一些更改:
if (characters.hasOwnProperty(key))
循环内无需检查:for in
。var obj = characters.key;
应为var obj = characters[key];
。if (obj.hasOwnProperty(prop))
。纠正这些事情(主要是#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."
]