日常练习小题目

388 阅读1分钟
  1. 扩展console.log方法,调用后打印的这条日志开头加上当前时间。
// console.log('hello', 'world'); 
// 输出“2020/3/22 上午11:20:20 - hello world”
window.console.log = (...a) => {
   return `${new Date().toLocaleString()} ${a.join(' ')}`
}
  1. 为字符串添加reverse方法,调用后将自己倒序排列。
String.prototype.reverse = function() {
    return this.split('').reverse().join('');
}
  1. 有一个数组里面只包含*和字母,写一个函数把所有的*都移动到左边,字母移动到右边,且字母顺序不能改变。
function move(arr) {
    const a = arr.filter(item => item === '*');
    const b = arr.filter(item => item !== '*');

    return a.concat(b);
}
  1. 实现一个函数比较两个版本号的大小,大于返回1,等于返回0,小于返回-1
var compareVersion = function(version1, version2) {
    const arr1 = version1.split('.').map(val => (+val));
    const arr2 = version2.split('.').map(val => (+val));
    const MaxLen = Math.max(arr1.length, arr2.length);

    for(let i = 0; i < MaxLen; i++) {
        const val1 = arr1[i] || 0;
        const val2 = arr2[i] || 0;

        if(val1 < val2) {
            return -1;
        } else if(val1 > val2) {
            return 1;
        } else if(val1 === val2) {
            continue;
        }   
    }
    return 0;
};
  1. 实现一个函数,将内敛样式中的 px (忽略大小写)改为 rem,并将数值除以 100
var px2rem = function (str) {
    const arr = str.match(/\d+px/g);

    for(let i = 0; i < arr.length; i++) {
        str = str.replace(arr[i], (str) => `${parseFloat(str) / 100 }rem`);
    }
     
    return str;
}

px2rem('width: 100px;fontWigth: 400;height: 300px;')
  1. 实现一个函数效果如同 document.getElementById,通过遍历 node.childNode 和 node.id 属性实现
// 简洁方法,但不满足题意
function getElementById (id) {
  return [].slice.call(document.all).find(node => node.id === id) || null;
}