簡體   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