基于另一个属性设置嵌套对象属性
我想计算字符在文本中出现的次数,然后显示每个字符的总计。我的主要问题是第一部分。基于另一个属性设置嵌套对象属性
这里是我的代码快照至今:
//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
的matches
的价值和count
值。
这个问题的最佳答案是最接近我解决我的问题。 Access/process (nested) objects, arrays or JSON
有迹象表明,应该对你的代码进行一些更改:
- 没有必要的检查:
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."
]
这太棒了。谢谢。你怎么能包括特殊字符,如不间断空格和标点符号? – joel
我会看看[这里](http://stackoverflow.com/questions/3115150/how-to-escape-regular-expression-special-characters-using-javascript)转义'c'在RegExp(c ,'g')'如果你超越了基本的字母数字。然后你需要删除字符数组的长度检查。 – tenub
再次,真棒,谢谢。我将其标记为答案。我唯一需要改变的就是删除长度检查(就像你所建议的那样),并且我在匿名结果对象的顶部添加了'character:c',以使其不那么匿名。另外,我似乎无法逃避'?'。 – joel
我已经可以发现有两件事情错了:1)没有必要的检查:'如果(characters.hasOwnProperty(密钥))'里面你'为in'循环。 2)你不能用点符号访问一个变量属性:'var obj = characters.key;'应该是'var obj = characters [key];'。 3)同样,不需要检查:'if(obj.hasOwnProperty(prop))'。纠正这些事情(主要是#2),它应该按照预期工作。 – tenub
嗯,我认为解决了这个问题,但我想我在Chrome控制台中出现了误报。 – joel