1、为字符串实现一个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
String.prototype.render = function (Object) {
  var _$this = this;
  var keys = new Array();
  for (var p in Object)
  if (Object.hasOwnProperty(p))
  keys.push(p);
  for (i = 0; i < keys.length; i++) {
    (function (index) {
      var s = '${' + keys[index] + '}';
      str = _$this.replace(s, Object[keys[index]]);
      _$this = str;
    }) (i);
  }
  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

String.prototype.render = function (Object) {
  var _this = this;
  for (var p in Object)
  if (Object.hasOwnProperty(p))
  {
    var s = '${' + p + '}';
    str = _this.replace(s, Object[p]);
    _this = str;
  }
  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

2.用js实现随机选取10–100之间的不同的10个数字,存入一个数组,并降序排序

    var aArray = [
    ];
    var i = 0;
    for (i = 0; i < 10; i++) {
      randomNub();
    }
    aArray.sort(function (a, b) {
      return b - a
    });
    document.write(aArray)
    function randomNub() {
      var nowNub = parseInt(Math.random() * 100);
      if (nowNub < 10) {
        randomNub();
        return;
      }
      for (var j = 0; j < aArray.length; j++) {
        if (nowNub == aArray[j]) {
          randomNub();
          return;
        }
      }
      aArray.push(nowNub);

}

3、下面代码希望在点击每段内容的时候给它加个灰色背景,可是下面这段代码好像没有满足需求,请帮忙修改下。

for (var i = 0; i < document.getElementsByTagName('p').length; i++) {
  var item = document.getElementsByTagName('p') [i];
  (function (j) {
    document.getElementsByTagName('p') [i].onclick = function () {
      item.style.backgroundColor = '#eee';
    }
  }(i))
}
//修改后
for (var i = 0; i < document.getElementsByTagName('p').length; i++) {
  var item = document.getElementsByTagName('p') [i];
  (function (j) {
    document.getElementsByTagName('p') [i].onclick = function () {
      this.style.backgroundColor = '#eee';
    }
  }(i))
}

hexy_xiaojie
125 声望0 粉丝

web前端,html,javascript,jQuery。