Let's talk about how to get all the parameters on the url and save them in the form of objects, and then talk about JSON parsing and serialization

foreword

大家好,我是梁木由,一个有想头的前端,最近呢也在为明年跳槽做复习准备。但我有个朋友呢,打算在年前跳槽,这不这几天正在疯狂面试中,前两天问了我两个问题,说是面试中遇到的。我看了下问题,思考的久久不能自拔,有个大概的模糊的想法,但是呢具体的写法还真没思考出来,于是呢便去查了查,给大家整理了出来

Intercept string parameters

How to get all the parameters on the url and display them in the form of objects

Implementation steps

  • First you need to get the url parameter part
  • Declare an object that holds the parameters
  • Divide each pair of parameters into an array and save
  • Traverse each pair of parameters, then get the key-value pair, and store it in the object that saves the parameters
  • Note that decodeURIComponent needs to be decoded for Chinese
function getQueryStringArgs(){
    
    
  // 取得参数字符串并去掉问号
  let params = location.search.length > 0 ? location.search.substring(1) : '',
        // 声明保存参数的对象
        args = {
    
    },
        // 保存每对参数
        items = params.length ? params.split('&') : [],
        // 存储键值对
        item = null,
        // 键
        name = null,
        // 值
        value = null,
        len = items.length;
  
  // 遍历每对参数
  for(let i = 0; i < len; i++){
    
    
    // 获取键值对
    item = items[i].split('=');
    name = decodeURIComponent(item[0]);
    value = decodeURIComponent(item[1]);
    
    // 将每一对参数都添加到args中
    if(name.length){
    
    
      args[name] = value
    }
  }
  return args
}

JSON parsing and serialization

I believe that everyone often uses the two methods stringify() and parse() of JSON objects. Do you know their complete usage?

parse

Parse a JSON string into a native javascript object

JSON.parse(text[, reviver])

  • text must pass a valid JSON string to be parsed into a JavaScript value
  • reviver Optional, a function to transform the result, this function will be called for each member of the object, used to modify the original value generated by parsing before returning the result
const str  = '{"date":"2023-01-11T03:24:36.398Z","time":"111","aa":null}'
const jsonStr = JSON.parse(str)
console.log(jsonStr) // { date: '2023-01-11T03:24:36.398Z', time: '111', aa: null }
const jsonStr1 = JSON.parse(str,(key, value) => {
    
    
  if(key === 'date'){
    
    
      return new Date(value)
  }else {
    
    
      return value
  }
})
console.log(jsonStr1.date.getFullYear()) //2023

stringify

Serialize a JavaScript object to a JSON string

JSON.stringify(value[, replacer[, space]])

  • value is the first parameter, the value to be serialized into a JSON string

  • replacer is optional. function or array to transform the result

    If replacer is a function, JSON.stringify will call the function, passing in the key and value for each member. Use the return value instead of the original value. If this function returns undefined, the member is excluded. The root object's key is an empty string: "".

    If replacer is an array, only members of the array that have a key value are converted. Members are converted in the same order as the keys are in the array. When the value parameter is also an array, the replacer array is ignored

  • space is optional, add indentation, spaces and line breaks to the text, if space is a number, the return value text is indented by the specified number of spaces at each level, if space is greater than 10, the text is indented by 10 spaces. Space can also use non-numbers, such as: \t.

value parameter

Let's take a look at the first demo, the basic usage of JSON.stringify()

var obj = {
    
    
    date: new Date(),
    time:'111',
    aa:null,
    vv:undefined
}
console.log(JSON.stringify(obj)) // {"date":"2023-01-11T03:24:36.398Z","time":"111","aa":null}

Have you noticed that it obj.vvis lost after passing through stringfiy, why is it because JSON.stringifyfields whose values ​​are undefined will be ignored during the conversion process.

replacer parameter

Next, look at the second demo, the usage of the replacer parameter

When the parameter is a function , the original value can be modified. Where can it be used? For example, JSON.stringify() needs to be used in the project, but if you want to keep it as a defined field, you can convert it first

var obj = {
    
    
  date: new Date(),
  time:'111',
  aa:null,
  vv:undefined
}
console.log(
  JSON.stringify(obj, (key,value) => {
    
    
    if(typeof value == 'undefined'){
    
    
      return true
    }
    return value
  })
)
// {"date":"2023-01-11T06:30:26.702Z","time":"111","aa":null,"vv":true}

When the parameter is an array, only the value of the date attribute is retained

var obj = {
    
    
  date: new Date(),
  time:'111',
  aa:null,
  vv:undefined
}
console.log(
  JSON.stringify(obj,['date'])
)
//{"date":"2023-01-11T06:33:20.772Z"}

space parameter

The blank string used to control indentation seems to be useless

var obj = {
    
    
  date: new Date(),
  time:'111',
  aa:null,
  vv:undefined
}
console.log(
  JSON.stringify(obj,'',2)
)
/*{
  "date": "2023-01-11T06:37:39.995Z",
  "time": "111",
  "aa": null
*/}
console.log(
  JSON.stringify(obj,'',10)
)
/*{
          "date": "2023-01-11T06:38:53.998Z",
          "time": "111",
          "aa": null
*/}

Guess you like

Origin blog.csdn.net/weixin_55123102/article/details/129122845