1.写一个深度克隆方法(es5)?
/** * 深拷贝 * @param {object}fromObj 拷贝的对象 * @param {object}toObj 目标对象 */
function deepCopyObj2NewObj(fromObj, toObj) {
for(var key in fromObj){
// 1. 取出键值对
var fromValue = fromObj[key];
// 2. 检查当前的属性值是什么类型 if(!isObj(fromValue)){
// 若是是值类型,那么就直接拷贝赋值 toObj[key] = fromValue; }else {
// 若是是引用类型,
// 那么就再调用一次这个方法,
// 去内部拷贝这个对象的全部属性
var tempObj = new fromValue.constructor; console.log(fromValue.constructor); deepCopyObj2NewObj(fromValue, tempObj); toObj[key] = tempObj; } } }
/** * 辅助函数, 判断是不是对象 * @param {object}obj * @returns {boolean} */
function isObj(obj) {
return obj instanceof Object; }
2. es6中let,const,var的区别是什么?
var :声明全局变量;
let :声明块级变量,即局部变量, 定义后能够修改;
const :用于声明常量,就是定义后 不能再修改值或者引用值的常量, 也具备块级做用域
3. 对数组[1,2,3,8,2,8]进行去重,es5或者es6方法?
es四种方式:
Array.prototype.unique1 = function() {
// 1. 定义数组 var temp = [];
// 2. 遍历当前数组 for(var i = 0; i < this.length; i++) {
// 3.若是当前数组的第i已经保存进了临时数组,
// 那么跳过,不然把当前项push到临时数组里面 if (-1 === temp.indexOf(this[i])) { temp.push(this[i]); } }
return temp; };
Array.prototype.unique2 = function() {
//1. hash为hash表,r为临时数组 var hash = {}, temp=[];
// 2.遍历当前数组
for(var i = 0; i < this.length; i++) {
// 3. 若是hash表中没有当前项
if (!hash[this[i]]) {
// 4.存入hash表 hash[this[i]] = true;
// 5.把当前数组的当前项
// push到临时数组里面
temp.push(this[i]); } }
return temp; };
Array.prototype.unique3 = function() {
var n = [this[0]];
for(var i = 1; i < this.length; i++){
if (this.indexOf(this[i]) === i) { n.push(this[i]); } }
return n; };
Array.prototype.unique4 = function() {
this.sort();
var re=[this[0]];
for(var i = 1; i < this.length; i++) {
if( this[i] !== re[re.length-1]) { re.push(this[i]); } }
return re;
}; es6:Array.prototype.unique=Array.prototype.unique || function () {
return [...new Set(this)]; };
4. 说说对es6中=>的理解?
箭头函数至关于匿名函数,
而且简化了函数定义,
箭头左边是参数,
右边是返回值。
箭头函数看上去
是匿名函数的一种简写,
但实际上,箭头函数和
匿名函数有个明显的区别:
箭头函数内部的this是词法做用域, 由上下文肯定。
5. 点击一个按钮,发出ajax请求,如何防止用户在此请求方式返回以前再次点击?
// 点击提交按钮的时候,
// 把这个提交这个处理函数给解绑掉,
// 请求完成的时候在绑定回来
function clickHandler(){ $(this).unbind('click', clickHandler); $.ajax({
url : 'url',
dataType : 'json',
type : 'post',
success : function (data) {
if (data.success) {
//提交成功作跳转处理 } else {
//处理失败,从新绑定点击事件 $(self).click(clickHandler); } } }
);}
$('#itlike').click(clickHandler);
// 能够点击后让按钮不可用,
// 若是提交失败能够再次设置为可用
// 1.让按钮不可用
$("#itlike").attr("disabled","disabled"); $.ajax({
url : 'url',
dataType : 'json',
type : 'post',
success : function (data) {
if (data.success) {
// 提交成功作跳转处理
} else {
// 处理失败,从新绑定点击事件
// 让按钮可用
$("#itlike").removeAttr("disabled"); } } });