![](/img/trans.png)
[英]Transferring Properties from one to another object based on the value of another property
[英]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
您应该对代码进行几处更改:
for in
循环中的if (characters.hasOwnProperty(key))
。 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."
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.