利用for 循环模拟 api
模拟 push
var arr = [1,2]
// arr.push(3)
function arr_push(arr,addItem){
arr[arr.length] = addItem
return arr.length
}
var len = arr_push(arr,3) //[1,2,3]
console.log(len,arr);
模拟concat
var a = [1,2]
var b = [3,3,[1,23]]
var res = a.concat(b)
console.log(res,a);
function arr_concat(){
var parms = [...arguments]
console.log(parms);
var res = [];
for(var i = 0;i<parms.length;i++){
parms[i].forEach(function(item){
res.push(item)
})
}
return res;
}
var res1 = arr_concat(a,b)
模拟实现 reverse
function arr_reverse(arr) {
var result = [];
// for(var i = arr.length-1;i>=0;i--){
// result.push(ar[i])
// }
for (var i = 0, len = arr.length; i < len; i++) {
result.unshift(arr[i])
}
return result;
}
var res = arr_reverse([1, 2, 2, 3, 3, 4, 5]
)
// 模拟pop
// 返回删除后数组
function arr_pop(arr) {
var newArr = []
for (var i = -0; i < arr.length - 1; i++) {
newArr[i] = arr[i]
}
arr = newArr;
return newArr
}
var arr1 = [1, 2, 3, 4, 5]
console.log(arr_pop(arr1));
模拟toString();
参数 arr
返回:组中元素链接的字符串
function arr_toString(arr) {
var result = '';
for(var i = 0,len= arr.length;i<len;i++){
// result = result + arr[i]+','
result += arr[i] +','
}
result = result.slice(0,result.length-1)
return result
}
var arr = [1, 2, 4, 5]
var res = arr_toString(arr);
console.log(res);
模拟 join()
function arr_join(arr,str){
var result = '';
for(var i = 0,len= arr.length;i<len;i++){
// result = result + arr[i]+str
result += arr[i] +str
}
result = result.slice(0,result.length-1)
return result
}
var res =arr_join([1,2,3,4],'+')
console.log(res);
slice()
返回街区的片段数组
参数 arr 其实索引与借宿索引
function arr_alice(arr, startIndex, lastIndex) {
// 错误优先原则
// 把错误对象放在最顶端
// 验证参数长度
if (arguments.length < 2) throw new Error('arguments of length is two')
if (!Array.isArray(arr)) throw new Error('parms1 must be array');
if (typeof startIndex !== 'number') throw new Error('parms2 must be Number')
// 验证第三个参数;要么是 undefined 要么是 number
if (typeof lastIndex !== 'undefined') {
if (typeof lastIndex !== 'number') throw new Error('parms3 must be Number or undefined')
}
var result = [];
// 便利arr
for (var i = 0, len = arr.length; i < len; i++) {
// 添加条件
// i> startIndex i<lastIndex
if (i >= startIndex && i < lastIndex) {
result.push(arr[i])
}
// 当i>=startIndex lastInex =undefined
if (i >= startIndex) {
result.push(arr[i])
}
}
return result;
}
// var arr = [1, 1, 1, 2, 2, 2, 2, 2]
// var res = arr_alice(arr, 3)
// console.log(res);
console.log(arr_alice([1, 2, 2],1));