Front-end interviewer: Can you implement the method on the js array prototype?

       An interviewer asked me: Can you use for or while to implement most of the methods on the js array prototype? I was very confused at the time, I didn’t try it myself and I didn’t know if it could be done, but I didn’t think it was too difficult, so I said: Yes! 很遗憾,后面他也祝我早日找到更匹配的工作了~

       Later, I tried to implement it myself. In the process, some methods were relatively simple. If there are deficiencies, I hope that some big brothers will give me advice, and there are some methods that I can't achieve: sort, reduceetc. But it can also achieve most of them. For some methods, I have written the implementation ideas 可能写得不清楚,, but I have not written the methods to implement the ideas, so I cannot explain them. Just look at the code and understand! ! !

at

       Official explanation: at()The method receives an integer value and returns the item at that index, allowing positive and negative numbers. Negative integers count down from the last item in the array. Rough meaning: Given an index, return the value of the current index.


Ideas:

  • When the passed index is greater than 0, the current index value is returned directly.
  • When the passed index is less than 0, return the penultimate ielement, formula: this.length + i .
  • When the passed index is equal to 0, the first element is returned directly.
const sect = ['少林派', '武当派', '逍遥派', '峨眉派', '华山派', '日月神教', '古墓派', '全真教', '丐帮', '明教']


Array.prototype.myAt = function(i) {
    
    
	let index = parseInt(i)

	if (index > 0) {
    
    
		return this[index]
	} else if (index < 0) {
    
    
		return this[this.length + index]
	} else {
    
    
		return this[0]
	}
}

const value = sect.myAt(3)
const value1 = sect.myAt(-1)

console.log('原数组:', sect)
console.log(value)
console.log(value1)

insert image description here

concat

       Official explanation: concat()The method is used to merge two or more arrays. This method does not alter the existing array, but returns a new array.

Ideas:

First prepare an empty array, then traverse the original array, and put all the values ​​into the prepared empty array, which is exactly the same as the original array.

  • When no parameters are passed (arguments.length < 1), return this array directly
  • When no parameters are passed (arguments.length >= 1), the actual parameters are traversed:
    • When the current actual parameter is not an array, it is directly inserted into the previously prepared array.
    • When the current actual parameter is an array, traverse the array and insert one by one into the previously prepared array.
const array1 = ['倚天屠龙记', '射雕英雄传'];
const array2 = ['笑傲江湖', '神雕侠侣'];


Array.prototype.myConcat = function() {
    
    
	let temp = []

	for (let u = 0; u < this.length; u++) {
    
    
		temp.push(this[u])
	} 

	// 当不传参数时
	if (arguments.length < 1) {
    
    
		return temp;
	}

	// 如果有参数,遍历实参
	for (let i = 0; i < arguments.length; i++) {
    
    
		// 当前实参
		let currentArg = arguments[i]
		// 当实参不是数组类型
		if (Object.prototype.toString.call(currentArg) !== '[object Array]') {
    
    
			temp.push(currentArg)
		} else {
    
    
			for (let j = 0; j < currentArg.length; j++) {
    
    
				temp.push(currentArg[j])
			}
		}
	}

	return temp
}

let array3 = array1.myConcat()
let array4 = array1.myConcat(array2)
let array5 = array1.myConcat(array2, '天龙八部')

console.log(array3)
console.log(array4)
console.log(array4)

insert image description here

every

       Official explanation: every()The method tests whether all elements in an array can pass the test of a specified function. It returns a boolean value.

Ideas:

First judge whether the passed in is a function, if not a function, throw an error! If it is a method, traverse this array, execute the callback function and pass the currently traversed value, index, and the entire array. If the callback function returns false, directly return false, if the entire array is traversedreturn true

const array1 = [1, 30, 39, 29, 10, 13]


Array.prototype.myEvery = function(fun) {
    
    
	let isFunction = Object.prototype.toString.call(fun) === '[object Function]'

	if (!isFunction) {
    
    
		throw new Error('请传入一个方法。')
	}
		
	// 遍历当前数组,执行回调函数并传入当前遍历的值
	for (let i = 0; i < this.length; i++) {
    
    
		let flag = fun(this[i], i, this)
		if (!flag) {
    
    
			return false
		}
	}

	 return true
}

console.log(array1.myEvery(item => item < 50))
console.log(array1.myEvery(item => item < 20))

insert image description here

fill

       Official explanation: fill()The method fills all elements in an array from the start index to the end index with a fixed value. Does not include terminating index.

Ideas:

Prepare an empty array and traverse this array:

  • When passing a parameter, insert this parameter into an empty array,
  • When passing two parameters,
    • When the traversed value is less than the second parameter, insert the value of the array into the array just prepared.
    • When the traversed index is equal to or greater than the second parameter, insert the first parameter into the array just prepared.
  • When passing three parameters, the same is true! ! !
const array1 = [1, 2, 3, 4];


Array.prototype.myFill = function() {
    
    
	let temp = []
	let leng = arguments.length

	for (let i = 0; i < this.length; i++) {
    
    
		if (leng === 1) {
    
    
			temp.push(arguments[0])
		} else if (leng === 2) {
    
    
			let start = parseInt(arguments[1])
			if(i < start) {
    
    
				temp.push(this[i])
			} else {
    
    
				temp.push(arguments[0])
			}
		} else {
    
    
			let start = parseInt(arguments[1])
			let end = parseInt(arguments[2])
			if(i < start || i >= end) {
    
    
				temp.push(this[i])
			} else {
    
    
				temp.push(arguments[0])
			}
		}
	}

	return temp
}

const array2 = array1.myFill(8)
const array3 = array1.myFill(8, 1)
const array4 = array1.myFill(8, 1, 3)

console.log(array2)
console.log(array3)
console.log(array4)

insert image description here

filter

       Official explanation: filter()The method creates a shallow copy of a portion of the given array, which contains all elements that pass the test implemented by the provided function. Rough meaning: Filter out the data you want from the array.

Ideas:

First judge whether the parameter is a function, not a function, and throw an error! If it is a function, traverse this array, execute the callback function, when the callback function returns true, insert the current value into the prepared empty array, and finally return this array.

const sect = ['少林派', '武当派', '逍遥派', '峨眉派', '华山派', '日月神教', '古墓派', '全真教', '丐帮', '明教']


Array.prototype.myFilter = function(fun) {
    
    
	let isFunction = Object.prototype.toString.call(fun) === '[object Function]'

	if (!isFunction) {
    
    
		throw new Error('请传入一个方法。')
	}

	let temp = []

	for (let i = 0; i < this.length; i++) {
    
    
		let flag = fun(this[i], i, this)

		if (flag) {
    
    
			temp.push(this[i])
		}
	}

	return temp
}

let newSect = sect.myFilter(item => item.length === 2)

console.log(newSect)

insert image description here

find

       Official explanation: find()The method returns the value of the first element in the array that satisfies the provided test function. Otherwise return undefined.

Ideas:

First judge whether the parameter is a function, not a function, and throw an error! If it is a function, traverse this array, execute the callback function, and if the callback function returns true, returntraverse the current value in it. If the traversal is over and the callback function does not return true, thenreturn undefined

const array1 = [5, 12, 8, 130, 44];

Array.prototype.myFind = function(fun) {
    
    
	let isFunction = Object.prototype.toString.call(fun) === '[object Function]'

	if (!isFunction) {
    
    
		throw new Error('请传入一个方法。')
	}

	for (let i = 0; i < this.length; i++) {
    
    
		let target = fun(this[i], i, this)
		if (target) {
    
    
			return this[i]
		}
	}
	
	return undefined
}

console.log(array1.myFind(item => item > 20));
console.log(array1.myFind(item => item > 200));

insert image description here

findLast

       Official explanation: findLast()The method returns the value of the last element in the array that satisfies the conditions of the provided test function. Returns if no corresponding element is found undefined.

Ideas:

The principle is the findsame, except that when looping the array, loop from right to left.

const array1 = [5, 12, 8, 130, 44]


Array.prototype.myFindLast = function(fun) {
    
    
	let isFunction = Object.prototype.toString.call(fun) === '[object Function]'

	if (!isFunction) {
    
    
		throw new Error('请传入一个方法。')
	}

	for (let i = this.length - 1; i >= 0; i--) {
    
    
		let target = fun(this[i], i, this)
		if (target) {
    
    
			return this[i]
		}
	}
	return undefined
}

console.log(array1.myFindLast(item => item > 20))
console.log(array1.myFindLast(item => item > 200))

insert image description here

findIndex

       Official explanation: findIndex()The method returns the index of the first element in the array that satisfies the provided test function. Returns -1 if no corresponding element is found.

Ideas:

First judge whether the parameter is a function, not a function, and throw an error! If it is a function, traverse this array, execute the callback function, and if the callback function returns true, returntraverse the current index in the array. If the traversal is over and the callback function does not return true, thenreturn -1

const array1 = [5, 12, 8, 130, 44]


Array.prototype.myFindIndex = function(fun) {
    
    
	let isFunction = Object.prototype.toString.call(fun) === '[object Function]'

	if (!isFunction) {
    
    
		throw new Error('请传入一个方法。')
	}

	for (let i = 0; i < this.length; i++) {
    
    
		let target = fun(this[i], i, this)
		if (target) {
    
    
			return i
		}
	}
	
	return -1
}

console.log(array1.myFindIndex(item => item > 10));
console.log(array1.myFindIndex(item => item > 1000));

insert image description here

findLastIndex

       Official explanation: findLastIndex()The method returns the index of the last element in the array that satisfies the conditions of the provided test function. If no corresponding element is found, -1 is returned.

Ideas:

The principle is the findIndexsame, except that when looping the array, loop from right to left.

const array1 = [5, 12, 8, 130, 44]
        

Array.prototype.myFindLastIndex = function(fun) {
    
    
	let isFunction = Object.prototype.toString.call(fun) === '[object Function]'

	if (!isFunction) {
    
    
		throw new Error('请传入一个方法。')
	}

	for (let i = this.length - 1; i >= 0; i--) {
    
    
		let target = fun(this[i], i, this)
		if (target) {
    
    
			return i
		}
	}
	
	return -1
}

console.log(array1.myFindLastIndex(item => item > 10))
console.log(array1.myFindLastIndex(item => item > 1000))

insert image description here

forEach

       Official explanation: forEach()The method executes the given function once for each element of the array.

const sect = ['少林派', '武当派', '逍遥派', '峨眉派', '华山派', '日月神教', '古墓派', '全真教', '丐帮', '明教']


Array.prototype.myForEach = function(fun) {
    
    
	let isFunction = Object.prototype.toString.call(fun) === '[object Function]'

	if (!isFunction) {
    
    
		throw new Error('请传入一个方法。')
	}

	for (let i = 0; i < this.length; i++) {
    
    
		fun(this[i], i, this)
	}
}

sect.myForEach((item, i, arr) => console.log(item, i, arr))

insert image description here

includes

       Official explanation: forEach()The method is used to judge whether an array contains a specified value, according to the situation, return if it contains true, otherwise return false.

Ideas:

Traverse the array, one by one to determine whether the parameters and the current value of the traversal are equal, if they are equal return true, otherwisereturn false

const sect = ['少林派', '武当派', '逍遥派', '峨眉派', '华山派', '日月神教', '古墓派', '全真教', '丐帮', '明教']


Array.prototype.myIncludes = function(value) {
    
    
	if (!value) {
    
    
		return false
	}

	for (let i = 0; i < this.length; i++) {
    
    
		if (value === this[i]) {
    
    
			return true
		}
	}

	return false
}

console.log(sect.myIncludes('明教'))
console.log(sect.myIncludes('伊斯兰'))

insert image description here

indexOf

       Official explanation: indexOf()The method returns the first index where the given element can be found in the array, or -1 if it does not exist.

const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];


Array.prototype.myIndexOf = function(target, index) {
    
    
	if (!target) {
    
    
		return -1
	}

	index = parseInt(index)
	let i = 0;
	if (index && index > 0 && index <= this.length) {
    
    
		i = index
	}
	if (index && index < 0 && index >= -(this.length)) {
    
    
		i = this.length + index
	}
	for (i; i < this.length; i++) {
    
    
		if (target === this[i]) {
    
    
			return i
		}
	}

	return -1
}

console.log(beasts.myIndexOf('bison'))
console.log(beasts.myIndexOf('bison', 4))

insert image description here

lastIndexOf

       Official explanation: lastIndexOf()The method returns the last index of the specified element (that is, a valid JavaScript value or variable) in the array, or -1 if it does not exist. Look forward from the back of the array, starting from fromIndex

const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];


Array.prototype.myLastIndexOf = function(target, index) {
    
    
	if (!target) {
    
    
		return -1
	}

	index = parseInt(index)
	let i = this.length - 1;
	if (index && index > 0 && index <= this.length) {
    
    
		i = index
	}
	if (index && index < 0 && index >= -(this.length)) {
    
    
		i = this.length + index
	}
	for (i; i >= 0; i--) {
    
    
		if (target === this[i]) {
    
    
			return i
		}
	}

	return -1
}

console.log(beasts.myLastIndexOf('bison'))
console.log(beasts.myLastIndexOf('bison', 4))

insert image description here

join

       Official explanation: join()The method concatenates all elements of an array (or an array-like object) into a string and returns the string. If the array has only one item, that item will be returned without a separator.

const elements = ['Fire', 'Air', 'Water']


Array.prototype.myJoin = function(target) {
    
    
	let str = ''

	for (let i = 0; i < this.length; i++) {
    
    
		if (!target) {
    
    
			str += this[i] + ','
		} else {
    
    
			str += this[i] + target
		}
				
	}
	return str.slice(0, str.length - 1)
}

console.log(elements.myJoin())
console.log(elements.myJoin('-'))
console.log([].myJoin()) // ''

insert image description here

map

       Official explanation: map()The method creates a new array consisting of the return value after calling the provided function once for each element in the original array.

Ideas:

First judge whether the parameter is a function, not a function, and throw an error! If it is a function, traverse this array, execute the callback function to pass in the current value, index, and this array of the traversal, insert the return value of the callback function into a temporary empty array, and finally this temporary array return.

const array1 = [5, 12, 8, 130, 44];


Array.prototype.myMap = function(fun) {
    
    
	let isFunction = Object.prototype.toString.call(fun) === '[object Function]'

	if (!isFunction) {
    
    
		throw new Error('请传入一个方法。')
	}

	let temp = []
	for (let i = 0; i < this.length; i++) {
    
    
		let value = fun(this[i], i, this)
		temp.push(value)
	}

	return temp
}

let map1 = array1.myMap(item => item + 2)
let map2 = array1.myMap(item => item / 2)

console.log('array1:', array1)
console.log(map1)
console.log(map2)

insert image description here

reverse

       Official explanation: reverse()The method reverses the position of the elements in the array and returns the array. The first element of the array becomes the last, and the last element of the array becomes the first. This method will change the original array.

const sect = ['少林派', '武当派', '逍遥派', '峨眉派', '华山派', '日月神教', '古墓派', '全真教', '丐帮', '明教']


Array.prototype.myReverse = function () {
    
    
	for (let i = 0; i < this.length / 2; i++) {
    
    
		let temp = this[i]
		let lastIndex = this.length - 1 - i
		this[i] = this[lastIndex]
		this[lastIndex] = temp
	}

	return this
}

let reSect = sect.myReverse()
console.log('改变后的数组:', sect)
console.log(reSect)

insert image description here

slice

       Official explanation: slice()The method returns a new array object, which is a shallow copy of the original array determined by begin and end (including begin, excluding end). The original array will not be changed.

const sect = ['少林派', '武当派', '逍遥派', '峨眉派', '华山派', '日月神教', '古墓派', '全真教', '丐帮', '明教']


Array.prototype.mySlice = function(begin, end) {
    
    
	let start = begin || 0
	let ending = end || this.length

	if (begin < 0) {
    
    
		start = this.length + begin
	}
	if (end < 0) {
    
    
		ending = this.length + end
	}

	let temp = []

	for (let i = start; i < ending; i++) {
    
    
		temp.push(this[i])
	}

	return temp
}

console.log(sect.mySlice(1, 3))
console.log(sect.mySlice(-2))

insert image description here

some

       Official explanation: some()The method tests whether at least one element in the array passes the provided function test. It returns a value of type Boolean.

const array1 = [5, 12, 8, 130, 44]

Array.prototype.mySome = function(fun) {
    
    
	let isFunction = Object.prototype.toString.call(fun) === '[object Function]'

	if (!isFunction) {
    
    
		throw new Error('请传入一个方法。')
	}

	for (let i = 0; i < this.length; i++) {
    
    
		let flag = fun(this[i], i, this)

		if (flag) {
    
    
			return true
		}
	}

	return false
}

console.log(array1.mySome(item => item === 130))
console.log(array1.mySome(item => item > 100))
console.log(array1.mySome(item => item > 200))

insert image description here

Guess you like

Origin blog.csdn.net/weixin_48165407/article/details/126919856