String仿照ajax的forEach()添加一个新的方法(初级前端面试)

题目要求:仿照ajax的forEach()向String中添加一个新的方法forEach()。其调用及应有效果eg:
'asasdassd'.forEach('a',function(item,index){console.log(item,index)})
//结果为0 ''     1 's'      2 'sd'        3 'ssd'

解答如下:

String.prototype.forEach=function(a,fun){
	var arr=this.split(a);
	for(var i=0,alen=arr.length;i<alen;i++){
		fun(i,arr[i]);
	}
}

直接利用String.prototype添加一个新的方法为forEach(),forEach需要两个参数,第一个是分割的字符a,第二个是一个方法fun。

值得注意的一点是fun()本身需要两个参数,即forEach()传递进来的两个参数分别对应index和item。


猜你喜欢

转载自blog.csdn.net/u013051947/article/details/79418135