算是检验自己对JavaScript理解一个很好的方法:
范例 :
const cat1 = {
name:"咪咪",
age:2,
color:"白色"
}
const cat2 = {
name:"妹妹",
age:1,
color:"虎斑"
}
const cat3 = {
name:"Toby",
age:2,
color:"虎斑"
}
const cats = [cat1,cat2,cat3]
Array.prototype.ownForEach = function(callback) {
for(let i = 0; i < this.length; i++) {
callback(this[i],i,this)
}
}
cats.ownForEach((cat) => {
console.log(cat)
})
//
{name: "咪咪", age: 2, color: "白色"}
{name: "妹妹", age: 1, color: "虎斑"}
{name: "Toby", age: 2, color: "虎斑"}
Array.prototype.ownMap = function(callback) {
const result = [];
for(let i = 0; i < this.length; i++) {
result.push(callback(this[i],i,this))
}
return result;
}
console.log(cats.ownMap((item) => `一只${item.color}的猫`))
// ["一只白色的猫", "一只虎斑的猫", "一只虎斑的猫"]
Array.prototype.ownFilter = function(callback) {
const result = [];
for(let i = 0; i < this.length; i++) {
if(callback(this[i],i,this)) {
result.push(this[i]);
}
}
return result;
}
console.log(cats.ownFilter((item) => item.color == '虎斑'))
//
0: {name: "妹妹", age: 1, color: "虎斑"}
1: {name: "Toby", age: 2, color: "虎斑"}
这边有另外一个写法 :
Array.prototype.ownFilter = function(callback) {
const result = [];
for(let i = 0; i < this.length; i++) {
callback(this[i],i,this) && result.push(this[i]) // 前者true就会执行後者
}
return result;
}
Array.prototype.ownEvery = function(callback) {
let isAllTrue = true;
for(let i = 0; i < this.length; i++) {
isAllTrue = callback(this[i],i,this);
if(!isAllTrue) break;
}
return isAllTrue;
}
console.log(cats.ownEvery((item) => item.age === 1)); // false
Array.prototype.ownSome = function(callback) {
let isTrue = false
for(let i = 0; i < this.length; i++) {
isTrue = callback(this[i],i,this);
if(isTrue) break
}
return isTrue;
}
console.log(cats.ownSome((item) => item.color === '黑色')); //false
Array.prototype.ownReduce = function(callback, initValue) {
let startIndex = 0;
let pre;
if(initValue || initValue===0) {
pre = initValue
} else {
pre = this[0];
startIndex = 1;
}
for(let i = startIndex; i < this.length; i++) {
pre = callback(pre, this[i], this)
}
return pre
}
const ageTotal = cats.ownReduce((pre,cur) => pre + cur.age,0);
console.log(ageTotal); // 5
驻列的目的是希望在幕後执行耗时的工作来加快反应时间,对於不熟悉驻列的人,Laracast一开始提供小...
缓存对於服务器的好处,在於使用者会将数据加载到内存,减少了对资料库的访问 终端输入 python m...
今天这篇是我们实作库米狗屋●KummyShop的情境电商模拟的最终章了!今天我们要把先前建的一堆订单...
这篇文章接下来我们要谈谈《 企业应用架构模式- Martin Fowler 》这本书中所提 doma...
这篇会稍微从前几篇的内容抽离出来,因为中秋节连假家人来找,只能先做点简单的事情... Android...