JavaScript 字符串数组及对象综合应用习题;

235 阅读3分钟
本人菜鸟一枚,写发low,大佬指点~~


一、动态向Url中添加参数

/** * 向 url 添加 query 参数 * * @param {string} targetUrl * @param {object} params */
function addQueryParam(targetUrl, params){   //Todo
}//输出

addQueryParam('https://cloud.tencent.com#hash', {a: 1,b: 1,c: 1})// 返回 https://cloud.tencent.com?a=1&b=1&c=1#hashconsole.log(addQueryParam('https://cloud.tencent.com?a=1&b=1#hash', {  b: 1}))// 返回 https://cloud.tencent.com?a=1&b=1#hashconsole.log(addQueryParam('https://cloud.tencent.com?a=1&b=1#hash', {  b: 2}))// 返回 https://cloud.tencent.com?a=1&b=2#hashaddQueryParam('https://cloud.tencent.com#hash', {a: 1,b: 1,c: 1})// 返回 https://cloud.tencent.com?a=1&b=1&c=1#hashconsole.log(addQueryParam('https://cloud.tencent.com?a=1&b=1#hash', {  b: 1}))// 返回 https://cloud.tencent.com?a=1&b=1#hashconsole.log(addQueryParam('https://cloud.tencent.com?a=1&b=1#hash', {  b: 2}))// 返回 https://cloud.tencent.com?a=1&b=2#hash

解法:

function toObj(params) {  let newObj = params.reduce((acc, cur) => {    var [key, value] = cur.split('=');    acc[key] = (value - 0) || undefined;    return acc;  }, {})  return newObj};function toStr(params) {  var arr = [];  for (let [key, value] of Object.entries(params)) {    arr.push(`${key}=${value}`)  }  return arr.join('&');}
function addQueryParam(targetUrl, params) {  // TODO  let newUrl;  let a = targetUrl.slice(0, targetUrl.indexOf('?') + 1);  let b = targetUrl.slice(targetUrl.indexOf('?') + 1, targetUrl.lastIndexOf('#'));  let hash = targetUrl.slice(targetUrl.lastIndexOf('#'));  if (targetUrl.indexOf('?') !== -1) {    if (b) {      c = b.split('&');      params = Object.assign(toObj(c), params);    }  }  let toQ = toStr(params);

  if (a) {    newUrl = `${a}${toQ}${hash}`  } else {    newUrl = `${b}?${toQ}${hash}`  }

  return newUrl}

二、金额千分位

function addComm(num){
    //Todo
}
addComm(1234)
//输出 1,234

解法一:

function addComm(num) {  //TODO  var c = (num.toString().indexOf ('.') !== -1) ?   num.toLocaleString() :    num.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,');  return c;}

解法二:浮点值情况

function thousands(num,end){  var splits=[],res=[];  var splits = num.toFixed(end).toString().split(".");  splits[0].split("").reverse().map(function(item,i){    if(i%3 == 0 && i!=0){ res.push(","); }    res.push(item);  });  return res.reverse().join("")+(splits.length>1 ? "."+splits[1] : "");}console.log(thousands(1234.666666666,2))
// 输入 1,234.67

三、Key首字符大写

const camelCasedData = {  age: 18,  gender: "female",  experiences: [{      from: "2009-09",      to: "2013-06",      exp: "School"    },    {      from: "2013-09",      to: "2020-02",      exp: "Job",    }  ],}

const camelToPascal = (input) => {  // TODO};

const pascalToCamel = (input) => {  // TODO};
const pascalCased = camelToPascal(camelCasedData);console.log(pascalCased);/* 期望输出:{  Age: 18,  Gender: "female",  Experiences: [      { From: "2009-09", To: "2013-06", Exp: "School" },      { From: "2013-09", To: "2020-02", Exp: "Job" },  ]}*/const camelCasedData2 = pascalToCamel(pascalCased);console.log(camelCasedData2)// 应该和 camelCasedData 一样


解法:

const camelToPascal = (input) => {  // TODO  let newObj = {};  let upperKey = (key) => key.replace(key[0], key[0].toUpperCase());  for (let [key, value] of Object.entries(input)) {    if (Array.isArray(value) && value.length > 0) {      newObj[upperKey(key)] = value.map((item) => {        if (JSON.stringify(item) !== "{}") {          return camelToPascal(item)        }      });    } else {      newObj[upperKey(key)] = value;    }  }  return newObj;};

const pascalToCamel = (input) => {  // TODO  let newObj = {};  let upperKey = (key) => key.replace(key[0], key[0].toLowerCase());  for (let [key, value] of Object.entries(input)) {    if (Array.isArray(value) && value.length > 0) {      newObj[upperKey(key)] = value.map((item) => {        if (JSON.stringify(item) !== "{}") {          return pascalToCamel(item)        }      });    } else {      newObj[upperKey(key)] = value;    }  }  return newObj;};


四、add(1)(2)(3)输出值等价于add(1,2,3)

function add(){

}
add(1)(2)(3) //6
add(1,2,3) //6

解法一:

function add () {  let sum = Array.from(arguments).reduce((acc, curr) => acc + curr, 0);

  function innerAdd() {    let _sum = Array.from(arguments).reduce((acc, curr)=> acc + curr, 0);    sum += _sum;    return innerAdd  }  innerAdd.toString = function(){    return sum  };  return innerAdd}var rusut=add(1)(2)(3).toString();console.log(rusut)


五、随机输出数字的顺序

Array.prototype.shuffle = function() {  var input = this;  for (var i = input.length-1; i >=0; i--) {      var randomIndex = Math.floor(Math.random()*(i+1));      console.log(randomIndex)      var itemAtIndex = input[randomIndex];      input[randomIndex] = input[i];      input[i] = itemAtIndex;  }  return input;}[1,2,3,4,5,6,7,8].shuffle();//[4, 6, 3, 2, 5, 1, 7, 8] // 每次结果都是随机的

解法:

/** * Fisher–Yates shuffle */Array.prototype.shuffle = function() {  var input = this;  for (var i = input.length-1; i >=0; i--) {      var randomIndex = Math.floor(Math.random()*(i+1));      console.log(randomIndex)      var itemAtIndex = input[randomIndex];      input[randomIndex] = input[i];      input[i] = itemAtIndex;  }  return input;}

六、展开多维数组

[1, [2, [3, 4], 5], 6]

//输出
[ 1, 2, 3, 4, 5, 6 ]

解法一:

function * flatten(array) {  for (const item of array) {    if (Array.isArray(item)) {      yield * flatten(item);    } else {      yield item;    }  }}const flattened = [...flatten([1, [2, [3, 4], 5], 6])];

解法二:

function flatten2(input) {  const stack = [...input];  const res = [];  while (stack.length) {    // 使用 pop 从 stack 中取出并移除值    const next = stack.pop();    if (Array.isArray(next)) {      // 使用 push 送回内层数组中的元素,不会改动原始输入      stack.push(...next);    } else {      res.push(next);    }  }  // 反转恢复原数组的顺序  return res.reverse();}

解法三:

function flatDeep(arr, d = 1) {  let newA = null;  if (d > 0) {    newA = arr.reduce(function(acc, val) {      if (Array.isArray(val)) {        return acc.concat(flatDeep(val, d - 1));      } else {        return acc.concat(val)      }    }, [])  } else {    newA = arr.slice();  }  return newA};console.log(flatDeep([1, [2, [3, 4], 5], 6],Infinity))

解法四:

function flatten(arr, d = 1) {  // TODO  return d > 0 ?    arr.reduce(      (acc, val) => acc.concat(        Array.isArray(val) ?        flatten(val, d - 1) :        val      ),      []) :    arr.slice();}let a = flatten([1, [2, [3, 4], 5], 6], Infinity);


后续有其他的继续添加,有其他解法的,大佬留言哈,学习一哈