分享一些面试遇到的问题
1、同源策略:
同源策略:浏览器安全策略,同协议、ip、端口的脚本才会执行;
跨域同源策略解决:带src属性的标签可以跨域。jsonp(json的一种使用模式):向服务端抛出一个callback方法,数据以参数传入,再有前端执行callback获得数据。
2、闭包:
for(var i=0;i<10;i++){
setTimeout(function(){
console.log(i);
},50);
}
输出都是10;
改进:
for(var i=0;i<10;i++){
(function(i){
setTimeout(function(){
console.log(i);
},50);
})(i);
}
3、对象深拷贝:
var a= { “child1” : 1, “child2” : { “key” : “value” } }
var b= copy(a);
实现:
function copy (obj) {
var newobj = {};
for (var i in obj) {
if (typeof obj[i] == "object") {
newobj[i] = copy(obj[i]);
} else {
newobj[i] = obj[i];
}
}
return newobj;
}
4、数组去重:实现:
Array.prototype.unique = function() {
var newArray = [];
var obj = {};
for (var i = 0; i < this.length; i++) {
if (!obj[this[i]]) {
newArray.push(this[i]);
obj[this[i]] = 1;
}
}
return newArray;
}
5、窗口变化调整方法优化:
function resizehandler() {
console.log('exe');
}
function throttle(method, context) {
clearTimeout(method.tId);
method.tId = setTimeout(function() {
method.call(context);
}, 200);
}
window.onresize = function() {
throttle(resizehandler, window);
}
6、css垂直居中显示:
第一种实现:
#parent { position: relative }
#child {
position: absolute;
width: 30%;
height: 20%;
top: 50%;
left: 50%;
margin: -10% 0 0 -15%;
}
第二种实现:
#parent { position: relative }
#child {
position: absolute;
width: 30%;
height: 20%;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto
}