every
<script>
Array.prototype.newEvery = function(fun){
//判断传入的是否为函数
if(typeof fun !== "function"){
throw new TypeError(`${fun} 不是一个函数`);
}
//循环遍历每一个元素
for(var i=0;i<this.length;i++){
//判断是否满足条件,满足输出false
if(!fun(this[i])){
return false;
}
}
return true;
}
var arr = [17,13,14,15,16,11];
var aa = arr.newEvery(function(value){
return value>12
})
console.log(aa);
</script>
pop
<script>
Array.prototype.newPop = function () {
if(this.length===0){
return this
}
//找到最后一个元素
var del = this[this.length-1];
//数组长度减1
this.length--;
//输出最后一个元素
return del;
}
var arr = [];
//最开始数组
console.log(arr);
//执行newPop方法
arr.newPop()
//打印删除的值
console.log(arr.newPop());
//打印删除之后的数组
console.log(arr);
</script>
shift
<script>
Array.prototype.newShift = function(){
var remove = this[0];
for(var i=1; i<this.length;i++){
this[i-1]=this[i]
}
this.length--
return remove
}
var arr = [11,22,33,44,55];
var val = arr.newShift();
console.log(val);
console.log(arr);
</script>
find
<script>
Array.prototype.newFind = function (fun) {
//判断传入的是否为函数
if (typeof fun !== "function") {
throw new TypeError(`${fun} 不是一个函数`);
}
//循环遍历
for (let i = 0; i < this.length; i++) {
//判断是否满足条件
if (fun(this[i])) {
return this[i];
}
}
}
var arr = [123, 456, 789];
const val = arr.newFind(function (value) {
return value
})
console.log(val);
</script>
join
<script>
Array.prototype.newJoin = function(){
//存放数据的容器
var string = ""
//循环遍历
for(var i=0;i<this.length;i++){
//判断数组中是否存在null和undifned
if(this[i] ===null ||this[i]===undefined){
this[i] = ""
}
//对i是否小于数组长度进行判断,符合就执行前面,不符合就执行后面,同时如果传入参数拼接的部分就传入参数,没有传入参数就默认,
string += (i<this.length-1) ? this[i] + (arguments[0] || ',') : this[i]
}
return string
}
var arr = [111,222,333,444]
var newarr = arr.newJoin('!')
console.log(newarr);
</script>
push
<script>
var arr = [111, 222, 333]
Array.prototype.newPush = function () {
let arglen = arguments.length;
let arrlen = this.length;
for (var i = 0; i < arguments.length; i++) {
this[arrlen + i] = arguments[i];
}
}
arr.newPush(22, 44, 66);
console.log(arr);
</script>
slice
<script>
var arr = [11,22,33,44,55];
// var val = arr.slice(1,2);
// console.log(val);
Array.prototype.newSlice = function(){
let start = 0;
let end =this.length;
if(arguments.length===1){
start =arguments[0];
}else if(arguments.length >= 2){
start = arguments[0];
end = arguments[1];
}
let newarr = [];
for(var i=start,j=0;i<end;i++,j++){
// newarr.push(this[i]);
newarr[j] = this[i]
}
return newarr;
}
var newarr = arr.newSlice(1,2)
console.log(newarr);
console.log(arr);
</script>
some
<script>
Array.prototype.newSome = function(fun){
//判断传入的是否为函数
if(typeof fun !== "function"){
throw new TypeError(`${fun} 不是一个函数`);
}
//循环遍历每一个元素
for(var i=0;i<this.length;i++){
if(fun(this[i])){
return true;
}
}
return false;
}
var arr = [10,11,12,15];
var bb = arr.newSome(function(value){
return value>12
})
console.log(bb);
</script>