Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

2015年3月31日,来做一道前端笔试题 #44

Open
xuyuan923 opened this issue Mar 31, 2015 · 8 comments
Open

2015年3月31日,来做一道前端笔试题 #44

xuyuan923 opened this issue Mar 31, 2015 · 8 comments

Comments

@xuyuan923
Copy link

/**
 * @fileoverview  为字符串实现一个render方法,实现下面的变量替换功能
 **/
var greeting = 'my name is $(name),age $(age)';
var result = greeting.render({name:'XiaoMing',age:11});
console.log(result); // my name is XiaoMing,age 11
@xuyuan923 xuyuan923 changed the title 来做一道前端笔试题 2015年3月31日,来做一道前端笔试题 Mar 31, 2015
@VaJoy
Copy link

VaJoy commented Mar 31, 2015

    String.prototype.render = function(option){
        var s = this,
                reg;
        Object.keys(option).forEach(function(k){
            reg = new RegExp("\\$\\("+k+"\\)","g");
            s = s.replace(reg,option[k])
        });
        return s
    };

    var greeting = 'my name is $(name),age $(age)';
    var result = greeting.render({name:'XiaoMing',age:11});
    console.log(result); // my name is XiaoMing,age 11

@think2011
Copy link
Collaborator

String.prototype.render = function (obj) {
    var str = this, reg;

    Object.keys(obj).forEach(function (v) {
        reg = new RegExp('\\$\\('+ v +'\\)', 'g');
        str = str.replace(reg, obj[v]);
    });

    return str;
}

var greeting = 'my name is $(name),age $(age)';
var result = greeting.render({name:'XiaoMing',age:11});
console.log(result); // my name is XiaoMing,age 11

感觉会有bug。

@VaJoy
Copy link

VaJoy commented Mar 31, 2015

@think2011 举个栗子?⊙﹏⊙

@think2011
Copy link
Collaborator

@VaJoy做过类似的题目,但是没通过测试,也是上面那样写的.. 后来没做完,有空找找那道题。

@lzzwoodtree
Copy link

String.prototype.render = function(obj){
var temp = this;
for (var p in obj) {
    var reg = new RegExp('\\$\\(' + p + '\\)', 'g');
    temp = temp.replace(reg, obj[p]);
}
return temp;
}

@lzzwoodtree
Copy link

我就传个low low的做法吧

@qingo
Copy link

qingo commented Aug 4, 2015

es6的字符串吧

var obj = {name:'XiaoMing',age:11}
`my name is ${obj.name},age ${obj.age}`

@singone
Copy link

singone commented Aug 18, 2015

String.prototype.render=function(object){

   return this.replace(/(?:\$\()(\w+)(?:\))/g,function(all,word){
        return object[word]||''
    });

};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants