Javascript 克罗克福德';使用多个级别对象替换

Javascript 克罗克福德';使用多个级别对象替换,javascript,Javascript,Crockford无疑是一个JavaScript大向导,但是当涉及到多个级别的对象时,他的原型是缺乏的 我希望这个函数能够涵盖多层对象替换,比如“{post.detailed}”,有人能帮我修改一下替换版本吗?这应该不会太难。请改用此替换功能: /** Supplant **/ String.prototype.supplant = function(o) { return this.replace (/{([^{}]*)}/g, function (a, b) {

Crockford无疑是一个JavaScript大向导,但是当涉及到多个级别的对象时,他的原型是缺乏的


我希望这个函数能够涵盖多层对象替换,比如“{post.detailed}”,有人能帮我修改一下替换版本吗?

这应该不会太难。请改用此替换功能:

/** 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;
        }
    );
};
功能(a、b){
var r=o,
部分=b.分割(“.”);

对于(var i=0;r&&i我个人讨厌人们用JavaScript在本机类型上塞满自己的垃圾。如果我要写它,我会做以下事情……但是为什么不喜欢布尔呢

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;
}
函数替换(str,data){
返回str.replace(/{([^{}]*)}/g,函数(a,b){
//将变量拆分为其点符号部分
var p=b.分割(/\./);
//c变量成为将遍历对象的游标
var c=数据;
//循环点符号路径中的步骤
对于(变量i=0;i

顺便说一句,它不支持数组,您需要做一些额外的工作来支持它。

@Bergi method w/support to boolean:

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;
    });
};
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;
}
祝你好运


这应该会有帮助:为什么您认为它不支持数组?只需使用
替换({myArray.0},{myArray:[“foo”]})
很好的调用!当然它会执行类型强制“0”=>0…Duh。事实上,它不是-属性名称总是字符串;数组对象也是如此。不正确。数组是数字索引的,您可以访问
arr[0]
而不是
arr[“0”]
,JavaScript非常聪明,能够理解您使用后者的意思。我认为您是完全正确的!如果
ToString(ToUint32(P))
等于
P
并且
ToUint32(P)
不等于
2^32,数组会给予特殊处理并将字符串属性
P
视为数组索引−1
。因此,事实上它是相反的
arr[0]
被强制为
arr[“0”]
而不是相反。
suppplant
现在正式成为一件事。请转到
npm安装suppplant
或访问。谢谢@Bergi
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;
            }
        );
    };
}