10081677wc / blog

78 stars 6 forks source link

前端面试题库 #3

Open 10081677wc opened 6 years ago

10081677wc commented 6 years ago

toFixed 兼容性实现

/* UPDATE */
Number.prototype.toFixed = function (s) {
    let num = this < 0 ? -this : this;
    let result = (parseInt(num * Math.pow(10, s) + 0.5) / Math.pow(10, s)).toString();
    let index = result.indexOf('.');

    if (index < 0 && s > 0) {
        result = result + '.';
        for (let i = 0; i < s; i++) result += '0';
    } else {
        index = result.length - index;
        for (let i = 0; i < (s - index) + 1; i++) result += '0';
    }

    return this < 0 ? -result : result;
};
Number.prototype.toFixed = function (s) {
    return (parseInt(this * Math.pow(10, s) + 0.5) / Math.pow(10, s)).toString();
} 

深拷贝和浅拷贝

var cloneObj = function(obj){
    var str, newobj = obj.constructor === Array ? [] : {};
    if(typeof obj !== 'object'){
        return obj;
    } else if(window.JSON){
        str = JSON.stringify(obj), //系列化对象
        newobj = JSON.parse(str); //还原
    } else {
        for(var i in obj){
            newobj[i] = typeof obj[i] === 'object' ? 
            cloneObj(obj[i]) : obj[i]; 
        }
    }

    return newobj;
};

input 标签 placeholder 的 JQuery 实现

$.fn.placeholder = function () {
    var ele = $(this);
    var defaultText = ele.data('placeholder') || 'Input placeholder here';
    var input = '';

    ele.val(defaultText);
    ele.focus(function () {
        if (input == '') {
            ele.val('');
        }
    }).blur(function () {
        if (ele.val() == '') {
            ele.val(defaultText);
        }
    }).change(function () {
        input = ele.val();
    });
};

翻转字符串

function reverseStr(str) {
    return str.split('').reverse().join('');
}

2 == [[2]]?

2 === Number([2].valueOf().toString()) // true
2 === Number([[2]].valueOf().toString()) // true

3.toString() & 3..toString()

3.toString() // Uncaught SyntaxError: Invalid or unexpected token
3..toString() // '3'

/* Because a decimal point is a valid portion of a number, so the first dot is considered numeric, the second is for chaining. */

正则表达式:驼峰化/中划线化

function camelize(str) {
    return str.replace(/[-_\s]+(.)?/g, function(match, c) {
        return c ? c.toUpperCase() : '';
    });
}

function dasherize(str) {
    return str.replace(/([A-Z])/g, '-$1').replace(/[-_\s]+/g, '-').toLowerCase();
}

console.log(camelize('-moz-transform')); // MozTransform
console.log(dasherize('MozTransform')); // -moz-transform