1. 如何实现数组去重?
假设有数组 array = [1,5,2,3,4,2,3,1,3,4]。你要写一个函数 unique,使得unique(array) 的值为 [1,5,2,3,4]。也就是把重复的值都去掉,只保留不重复的值。
- 不使用 Set,借鉴计数排序的原理
unique = (array) => {
const hash = []
for(let i=0;i<array.length; i++){
hash[array[i]] = true
}
const result = []
for(let k in hash){
result.push(k)
}
return result
}
这个是使用indexOf,比较数组下标,若在新数组中不存在该元素则添加进新数组,若有则说明重复。
const array = [1,5,2,3,4,2,3,1,3,4]
function unique(arr){
const table = []
arr.forEach(i => {
if(table.indexOf(i)==-1) table.push(i)
})
// 也可以直接使用filter
// return arr.filter((element, index) => arr.indexOf(element)===index )
return table
}
console.log(unique(array))
方案一缺点:只支持数字或者字符串数组,如果数组里面有对象,比如 array = [{number:1}, 2]
,就会出错。
接下来使用 Set
unique = (array) => {
return [...new Set(array)]
// 或者 return Array.from(new Set(array))
}
方案二缺点:API 太新,旧浏览器不支持。
接下来使用 Map
unique = (array) => {
let map = new Map();
let result = []
for (let i = 0; i < array.length; i++) {
if(map.has(array[i])) { // 判断 map 中是否已有该 key
continue
} else { // 如果 map 中没有该 key,就加入 result 中
map.set(array[i], true);
result.push(array[i]);
}
}
return result;
}
方案三缺点:API 太新,旧浏览器不支持。
2. DOM 事件相关
(1)什么是事件委托
就是把事情委托给别人代为处理。说白了, 就是子元素太多,就把需要处理的代码交给父元素的事件中进行处理。
(不监听元素 C 自身,而是监听其祖先元素 P,然后判断 e.target 是不是该元素 C(或该元素的子元素))
(2)怎么阻止默认事件
阻止默认动作:e.stopPreventDefault()
或者 return false
(3)怎么阻止事件冒泡?
阻止事件冒泡:e.stopPropagetion()
3. 如何理解 JS 的继承?
基于原型。原型链继承则是在原型基础上多加了几层,本质都是利用原型继承。
function Parent(name1){
this.name1 = name1
}
Parent.prototype.pMethod = function(){
console.log(this.name1)
}
function Child(name2, name1){
Parent.call(this, name1) // 重点
this.name2 = name2
}
Child.prototype.__proto__ = Parent.prototype
//上面这句代码的古板写法应该是下面三句
//const empty = function(){}
//empty.prototype = Parent.prototype
//Child.prototype = new empty()
Child.prototype.cMethod = function(){
console.log(this.name2)
}
基于 class
class Parent{
constructor(name1){
this.name1 = name1
}
pMethod(){
console.log(this.name1)
}
}
class Child extends Parent{
constructor(name2, name1){
super(name1) // 重点
this.name2 = name2
}
cMethod(){
console.log(this.name2)
}
}
3. 数组排序
给出正整数数组 array = [2,1,5,3,8,4,9,5]
请写出一个函数 sort,使得 sort(array) 得到从小到大排好序的数组 [1,2,3,4,5,5,8,9]
新的数组可以是在 array 自身上改的,也可以是完全新开辟的内存。
有多种排序方法,仅列出一种循环选择排序
let sort = (numbers) => {
for(let i=0; i<(numbers.length - 1); i++){
let index = minIndex(numbers.slice(i))+i
if(index != i){ swap(numbers, index, i) }
}
return numbers
}
let swap = (array, i, j) => {
let temp = array[i]
array[i] = array[j]
array[j] = temp
}
let minIndex = (numbers) => {
let index = 0
for( let i=1; i<numbers[index];i++ ){
if( numbers[i] < numbers[index] ){
index = i
}
}
return index
}
网友评论