1.解释DOCTYPE的作用
用来告知浏览器的解析器用什么文档标准解析文档
2.什么情况下会遇见跨域问题?有哪些解决方法?
不满足同源策略(协议、域名、端口)时会遇见跨域问题。
解决方法:jsonp、cors、代理服务器
3.如何理解闭包?使用闭包的注意点有哪些?
在js中,由于变量的作用域属于函数作用域,在函数执行后作用域就会被清理,内存也会随之被收回,但是闭包是建立在一个函数内部的子函数,由于其可访问上级作用域的原因,即使上级函数执行完,作用域也不会随之销毁。
注意点:滥用闭包会导致内存泄漏、会改变父函数内部变量的值。
4.请手写字符串数组去重函数
①Set方法
Array.prototype.unique=function(){
return [...new Set(this)]
}
②map方法
Array.prototype.unique=function(){
const map=new Map()
return this.filter(item=>{return !map.has(item)&&map.set(item,1)})
}
5.使用reduce函数来实现简单的数组求和
Array.prototype.sum=function(){
var sumResult=0;
return this.reduce(function(preValue,curValue){
return sumResult=preValue+curValue
})
return sumResult
}
6.手写push
定义:将一个或多个元素添加到数组的末尾并返回该新数组的长度
//在数组原型上定义一个新属性
Array.prototype.newPush=null;
//添加到数组末尾的方法
function push(){
if(!this.length){
this.length=0
}
if(isNaN(Number(this.length))){
this.length=0
}
for(let i=0;i<arguments.length;i++){
this[this.length]=arguments[i]
}
//返回新的数组长度
return this.length
}
//将push方法赋值给原型的新属性
Array.prototype.newPush=push
7.cookie,sessionStorage、localStorage的区别
cookie可以设置失效时间,但没有自己的存取方法,需要进行封装,而localStorage、sessionStorage有自己的存取方法比如steItem(),getItem()。
8.如何组织事件冒泡和默认事件
e.stopPropagation()
e.preventDefalut()
9.js怎样添加 移除 创建和查找节点
创建新节点: createElement()、createTextNode()、createDocumentFragment()
添加:appendChild()
移除:removeChild()
查找:getElementById()、getElementByTagName()、getElementByName()
10.js中如何检测一个变量是一个String类型?
三种方法:typeof、constructor、Object.prototype.toString.call()
typeof('123')==="String"
'123'.constructor===String
Object.prototype.toString.call('123')==='[object string]'