5
/** Supplant **/
String.prototype.supplant = function(o) {
    return this.replace (/{([^{}]*)}/g,
        function (a, b) {
            var r = o[b];
            return typeof r === 'string' || typeof r === 'number' ? r : a;
        }
    );
};

Crockfordは間違いなくJavaScriptGrandWizardですが、複数レベルのオブジェクトに関しては、彼のプロトタイプが不足しています。

この関数で「{post.detailed}」などの複数レベルのオブジェクト置換をカバーしたいのですが、誰かが代替バージョンの改訂版を手伝ってくれませんか?

4

3 に答える 3

5

それはそれほど難しくないはずです。代わりに、次の置換関数を使用してください。

function (a, b) {
    var r = o,
        parts = b.split(".");
    for (var i=0; r && i<parts.length; i++)
        r = r[parts[i]];
    return typeof r === 'string' || typeof r === 'number' ? r : a;
}
于 2012-10-16T08:32:03.497 に答える
3

個人的には、JavaScript のネイティブ型に自分のゴミを詰め込むのが嫌いです。私がそれを書くとしたら、次のようにします...しかし、ブール値が好きではないのはなぜですか?

function supplant(str, data) {
    return str.replace(/{([^{}]*)}/g, function (a, b) {

        // Split the variable into its dot notation parts
        var p = b.split(/\./);

        // The c variable becomes our cursor that will traverse the object
        var c = data;

        // Loop over the steps in the dot notation path
        for(var i = 0; i < p.length; ++i) {

            // If the key doesn't exist in the object do not process
            // mirrors how the function worked for bad values
            if(c[p[i]] == null)
                return a;

            // Move the cursor up to the next step
            c = c[p[i]];
        }

        // If the data is a string or number return it otherwise do
        // not process, return the value it was, i.e. {x}
        return typeof c === 'string' || typeof c === 'number' ? c : a;
    });
};

それは配列をサポートしていません。それをサポートするには、いくつかの追加作業を行う必要があります。

于 2012-10-16T08:35:00.153 に答える
2

ブール値をサポートする@Bergiメソッド:

function (a, b) {
    var r = o,
        parts = b.split(".");
    for (var i=0; r && i<parts.length; i++)
        r = r[parts[i]];
    return typeof r === 'string' || typeof r === 'number' || typeof r === 'boolean' ? r : a;
}

ブール値をサポートする元の Crockford の Supplant メソッド:

if (!String.prototype.supplant) {
    String.prototype.supplant = function (o) {
        return this.replace(/{([^{}]*)}/g,
            function (a, b) {
                var r = o[b];
                return typeof r === 'string' || typeof r === 'number' || typeof r === 'boolean' ? r : a;
            }
        );
    };
}

頑張ってください!

https://gist.github.com/fsschmitt/b48db17397499282ff8c36d73a36a8af

于 2016-07-22T09:40:04.317 に答える