JS原型一些方法

看图说话 栗子子在这里

var obj = {
  person: {
    name: 'joe',
    history: {
      hometown: 'bratislava',
      bio: {
        funFact: 'I like fishing.'
      }
    }
  }
};

obj.hash('person.name'); // 'joe'
obj.hash('person.history.bio'); // { funFact: 'I like fishing.' }
obj.hash('person.history.homeStreet'); // undefined
obj.hash('person.animal.pet.needNoseAntEater'); // undefined

关于原型的方法好像都不会哎   直接看答案啊!

best  practics

Object.prototype.hash = function(string) {
  var arr = string.split('.');
  return arr.reduce(function(pv, cv){
    return (pv) ? pv[cv] : pv;
  }, this);
}


//reduce 归并方法  四个参数 (pre next index array);
//返回值作为第一的参数传给下一项,第一次迭代发生在数组第二项上,第一个参数是数组第一项,第二项是数组第二项

reduce()方法再啰嗦两句 ,好像很牛逼的样子 

少年,我看你很有想法,来和我求和吧

var arr=[1,2,3,4,5];
m=arr.reduce(function(pre,next,index,this){
return pre+next;
});

alert(m);

//理解下上面的代码

还有个能看懂的理解下

Object.prototype.hash = function(string) {
  var current = this;
  var props = string.split('.');
  
  while (current && props.length) {
    current = current[props.shift()];
  }
  
  return current;
}

//shifit()方法  移除队列首项,和push  相反
原文地址:https://www.cnblogs.com/liuestc/p/4525730.html