![](/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.