美文网首页
JavaScript常用方法总结

JavaScript常用方法总结

作者: 华戈的小书 | 来源:发表于2019-03-27 15:34 被阅读0次

写一个function,清除字符串前后的空格

//answer one:
function trim(str) {
  if (str & typeof str === "string") {
    return str.replace(/^(\s*)|(\s*)$/g,""); //去除前后空白符
  }
}
//answer two:
var str = "   xiao  ming   ";
var str2 = str.trim();

判断一个字符串中出现次数最多的字符,统计这个次数

  • charAt(i) : 返回当前字符串下标的值 str.charAt(i) == str[i];
var str = 'asdfssaaasasasasaazzzzzzzzzz';
var json = {};
for (var i = 0; i < str.length; i++) {
  if(!json[str.charAt(i)]){
    json[str.charAt(i)] = 1;
  }else{
    json[str.charAt(i)]++;
  }
};
var iMax = 0;
var iIndex = '';
for(var i in json) {
  if (json[i]>iMax) {
    iMax = json[i];
    iIndex = i;
  }
}
alert('出现次数最多的是:'+iIndex+'出现'+iMax+'次');

编写一个方法 求一个字符串的字节长度

function getStrLength(str) {
  var count = str.length;
  for (var i in str) {
    if (str[i].charCodeAt() > 255) {
      count++;
    }
  }
  return count;
}
getStrLength('ss龙珠');

编写一个方法 去掉一个数组的重复元素

//es6
var arr = [1,2,3,4,3,2,1];
arr1 = [...new Set(arr)];
//answer one:
function removeCommon(){
  var json = {};
  for (var i = 0; i < str.length; i++) {
    json[str[i]] = str[i];
  }
var ss = [] ;
for (var i in json) ss.push(json[i]);
  return ss;
}
var str = [1,2,3,1,43,12,12,1,'s','s'];
removeCommon(str);
//answer two:
var arr = [0,2,3,4,4,0,2];
var obj = {};
var tmp = [];
for (var i = 0 ;i< arr.length;i++){
  if ( !obj[arr[i]] ) {
    obj[arr[i]] = 1;
    tmp.push(arr[i]);
  }
}
console.log(tmp);
//answer three:
var arr = [2,3,4,4,5,2,3,6],
arr2 = [];
for (var i = 0;i< arr.length;i++) {
  if (arr2.indexOf(arr[i]) < 0) {
    arr2.push(arr[i]);
  }
}
console.log(arr2);

JavaScript中如何检测一个变量是一个String类型?

typeof(obj) == 'string';
obj.constructor == String;

使用递归和循环实现1!+2!+3!+4!+...+15!

function rec(n) {
  if (n == 1) {
    return 1;
  } else {
    return n*rec(n-1);
  }
}
function init(m) {
  count = 0;
  for (var i = 1; i <= m; i++) {
    count  += rec(i);
  }
 }
init(15);
console.log(count);

输出今天的日期,以YYYY-MM-DD的方式

var date = new Date();
var year = date.getFullYear();
var month = date.getMonth()+1;
var data = date.getDate();
if (month < 10) {
  month = "0" + month;
}
if (data < 10) {
  data = "0" + data;
}
console.log(`${year}-${month}-${data}`);

已知有字符串foo=”get-element-by-id”,写一个function将其转化成驼峰表示法”getElementById”

function upper(foo) {
  var f1 = [];
  for (var i = 0; i < foo.length; i++) {
    if (foo[i] == "-") {
      f1.push(foo[++i].toUpperCase());
    } else {
      f1.push(foo[i]);
    }
  }
  console.log(f1.join(""));
}
var foo = "get-element-by-id";
upper(foo);

已知有一字符串str='hello word',写一个函数实现用空格隔开字符,即'h e l l o w o r d'

function spacify(e) {
  return e.split('').join(" ");
}
spacify('hello word');

字符串反转

var str = "dsawe";
var newStr = str.split('').reverse().join('');

浏览器URL中查询字符串中的参数转化为对象

function showWindowHref() {
  var sHref = window.location.href;
  var args = sHref.split('?');
  if (args[0] == sHref) {
    return "";
  }
  var arr = args[1].split('&');
  var obj = {};
  for (var i = 0; i< arr.length; i++) {
    var arg = arr[i].split('=');
    obj[arg[0]] = arg[1];
  }
  return obj;
}
var href = showWindowHref();

大数相加

function largeNumAdd(a,b) {
  const fir = a.split("").length,
        sec = b.split("").length;
  let result = [],
      maxLen,
      minLen,
      addflag = 0;
  if (fir > sec) {
    maxLen = fir;
    minLen = sec;
  } else {
    [a,b] = [b,a];
    maxLen = sec;
    minLen = fir;
  }
  for (let i = maxLen -1, j = minLen -1; i >= 0; i--, j--) {
    if (j>=0) {
      result.unshift(parseInt(a[i]) + parseInt(b[j]));
    } else {
      result.unshift(parseInt(a[i]));
    }
  }
  let len = result.length;
  for (let k = len-1; k >= 0; k--) {
    let temp = result[k];
    if (temp > 9) {
      if (k > 0) {
        result[k] = temp - 10;
        result[k-1] += 1;
      } else {
        result[k] = temp - 10;
        result.unshift(1)
      }
    }
  }
  return result.join("").replace(/^\s*/,"");
}
largeNumAdd('99999999999999999999999','9111111111111111111199');

大数相乘

function largeNumMul(a,b) {
    let str1 = a.split("").reverse(),
        str2 = b.split("").reverse(),
        lena = str1.length,
        lenb = str2.length,
        result = [];
    //初始化
    for(var i = 0; i < lena; i++) {
        for (var j = 0; j < lenb; j++) {
          result[i+j] = 0;
        }
    }
    // 乘法法则
    for (var i = 0; i < lena; i++) {
        for (var j = 0; j < lenb; j++) {
            result[i+j] += parseInt(str1[i])*parseInt(str2[j]);
        }
    }
    let len = result.length;
    if (result[len-1] > 9) {
        result[len] = 0;
    }
    for (let k = 0; k < len; k++) {
        let temp = result[k];
        if (temp > 9) {
            result[k] = temp % 10;
            result[k+1] += Math.floor(temp/10);
        }
    }
    return result.reverse().join("").replace(/^\s*/,"");
}
largeNumMul('9999999999999543453453','34534532342345345345555');

相关文章

网友评论

      本文标题:JavaScript常用方法总结

      本文链接:https://www.haomeiwen.com/subject/vcmzvqtx.html