<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          9 個(gè)JSON.stringify 的秘密大多數(shù)開(kāi)發(fā)人員卻不知道

          共 14459字,需瀏覽 29分鐘

           ·

          2023-01-18 11:51

          10af908ea440d8f64dc24114e3967ee1.webp

          英文 | https://javascript.plainenglish.io/as-a-front-end-engineer-9-secrets-about-json-stringify-you-should-know-about-e71c175f40d8

          作為前端開(kāi)發(fā)工程師,你一定用過(guò)JSON.stringify,但你知道它的全部秘密嗎? 很久以前,我因此在工作中犯下了無(wú)法挽回的錯(cuò)誤。如果我早點(diǎn)知道,就不會(huì)發(fā)生這樣的悲劇。 理解 JSON.stringify 基本上,JSON.stringify 將對(duì)象轉(zhuǎn)換為 JSON 字符串。同時(shí),JSON.stringify 有如下規(guī)則。

          fedc7414291f4766b10b5d3043ca8571.webp


          1. undefined、Function 和 Symbol 不是有效的 JSON 值。 如果在轉(zhuǎn)換過(guò)程中遇到任何此類值,它們要么被省略(當(dāng)在對(duì)象中找到時(shí)),要么更改為 null(當(dāng)在數(shù)組中找到時(shí))。 當(dāng)傳入像 JSON.stringify(function() {}) 或 JSON.stringify(undefined) 這樣的“純”值時(shí),JSON.stringify() 可以返回 undefined。

          8d5b086e3af463a43dc4e71aa5706dd2.webp

          2.Boolean、Number、String對(duì)象在字符串化過(guò)程中被轉(zhuǎn)換為對(duì)應(yīng)的原始值,符合傳統(tǒng)的轉(zhuǎn)換語(yǔ)義。

          b2aba54325c0011424a0f6185c1b5616.webp

          3.所有以符號(hào)為鍵的屬性將被完全忽略,即使在使用替換函數(shù)時(shí)也是如此。

          daf0966b5ed6ae91311cf8fa2b484b75.webp

          4. 數(shù)字 Infinity 和 NaN,以及值 null,都被認(rèn)為是 null。

          5429f76f0feb95fbcd553263a39684bc.webp

          5. 如果該值有一個(gè) toJSON() 方法,它負(fù)責(zé)定義哪些數(shù)據(jù)將被序列化。

          fc8f2e1e06d977ea0ff6cbcc80836ea6.webp

          6. Date實(shí)例通過(guò)返回字符串實(shí)現(xiàn)toJSON()函數(shù)(同date.toISOString())。? 因此,它們被視為字符串。

          e6c026cb7faad18adb135f198fb8cae7.webp

          7. 在包含循環(huán)引用的對(duì)象上執(zhí)行此方法會(huì)拋出錯(cuò)誤。

          1c3fd093b4a4d4730dbc4450ba327bb0.webp

          8. 所有其他對(duì)象實(shí)例(包括 Map、Set、WeakMap 和 WeakSet)將只序列化它們的可枚舉屬性。

          e4c4ca2b0d48e4cb5e0eee9f26f97874.webp

          9.嘗試轉(zhuǎn)換BigInt類型的值時(shí)拋出錯(cuò)誤。

          a18aa8242c611996cd23e2168975bb87.webp

          自己實(shí)現(xiàn) JSON.stringify 理解功能的最好方法是自己去實(shí)現(xiàn)它。 下面我寫(xiě)了一個(gè)簡(jiǎn)單的函數(shù)來(lái)模擬JSON.stringify。
                
                  const jsonstringify = (data) => {
                
                
                    // Check if an object has a circular reference
                
                
                    const isCyclic = (obj) => {
                
                
                    // Use the Set data type to store detected objects
                
                
                    let stackSet = new Set()
                
                
                    let detected = false
                
                
                  
                    
          const detect = (obj) => { // If it is not an object type, you can skip it directly if (obj && typeof obj != 'object') { return } // When the object to be checked already exists in the stackSet, it means that there is a circular reference if (stackSet.has(obj)) { return detected = true } // Save the current obj as a stackSet stackSet.add(obj)
          for (let key in obj) { if (obj.hasOwnProperty(key)) { detect(obj[key]) } } // After the level detection is completed, delete the current object to prevent misjudgment /* For example: an object's attribute points to the same reference. If it is not deleted, it will be regarded as a circular reference let tempObj = { name: 'fatfish' } let obj4 = { obj1: tempObj, obj2: tempObj } */ stackSet.delete(obj) }
          detect(obj)
          return detected }
          // 7#: // Executing this method on an object that contains a circular reference throws an error.
          if (isCyclic(data)) { throw new TypeError('Converting circular structure to JSON') }
          // 9#: An error is thrown when trying to convert a value of type BigInt // An error is thrown when trying to convert a value of type bigint if (typeof data === 'bigint') { throw new TypeError('Do not know how to serialize a BigInt') }
          const type = typeof data const commonKeys1 = ['undefined', 'function', 'symbol'] const getType = (s) => { return Object.prototype.toString.call(s).replace(/\[object (.*?)\]/, '$1').toLowerCase() }
          // not an object if (type !== 'object' || data === null) { let result = data // 4#:The numbers Infinity and NaN, as well as the value null, are all considered null. if ([NaN, Infinity, null].includes(data)) { result = 'null' // 1#:undefined, Function, and Symbol are not valid JSON values. // If any such values are encountered during conversion they are either omitted (when found in an object) or changed to null (when found in an array). // JSON.stringify() can return undefined when passing in "pure" values like JSON.stringify(function() {}) or JSON.stringify(undefined). } else if (commonKeys1.includes(type)) { return undefined } else if (type === 'string') { result = '"' + data + '"' }
          return String(result) } else if (type === 'object') { // 5#: If the value has a toJSON() method, it's responsible to define what data will be serialized. // 6#: The instances of Date implement the toJSON() function by returning a string (the same as date.toISOString()). // Thus, they are treated as strings. if (typeof data.toJSON === 'function') { return jsonstringify(data.toJSON()) } else if (Array.isArray(data)) { let result = data.map((it) => { // 1#: If any such values are encountered during conversion they are either omitted (when found in an object) or changed to null (when found in an array). return commonKeys1.includes(typeof it) ? 'null' : jsonstringify(it) })
          return `[${result}]`.replace(/'/g, '"') } else { // 2#:Boolean, Number, and String objects are converted to the corresponding primitive values during stringification, in accord with the traditional conversion semantics. if (['boolean', 'number'].includes(getType(data))) { return String(data) } else if (getType(data) === 'string') { return '"' + data + '"' } else { let result = [] // 8#: All the other Object instances (including Map, Set, WeakMap, and WeakSet) will have only their enumerable properties serialized. Object.keys(data).forEach((key) => { // 3#: All Symbol-keyed properties will be completely ignored, even when using the replacer function. if (typeof key !== 'symbol') { const value = data[key] // 1#: undefined, Function, and Symbol are not valid JSON values. if (!commonKeys1.includes(typeof value)) { result.push(`"${key}":${jsonstringify(value)}`) } } })
          return `{${result}}`.replace(/'/, '"') } } } }

          還有一個(gè)測(cè)試

                
                  
                    // 1. Test basic features
                  
                
                
                  console.log(jsonstringify(undefined)) // undefined 
                
                
                  console.log(jsonstringify(() => { })) // undefined
                
                
                  console.log(jsonstringify(Symbol('fatfish'))) // undefined
                
                
                  console.log(jsonstringify((NaN))) // null
                
                
                  console.log(jsonstringify((Infinity))) // null
                
                
                  console.log(jsonstringify((null))) // null
                
                
                  console.log(jsonstringify({
                
                
                    name: 'fatfish',
                
                
                    toJSON() {
                
                
                      return {
                
                
                        name: 'fatfish2',
                
                
                        sex: 'boy'
                
                
                      }
                
                
                    }
                
                
                  }))
                
                
                  
                    // {"name":"fatfish2","sex":"boy"}
                  
                
                
                  
                    
          // 2. Compare with native JSON.stringify console.log(jsonstringify(null) === JSON.stringify(null)); // true console.log(jsonstringify(undefined) === JSON.stringify(undefined)); // true console.log(jsonstringify(false) === JSON.stringify(false)); // true console.log(jsonstringify(NaN) === JSON.stringify(NaN)); // true console.log(jsonstringify(Infinity) === JSON.stringify(Infinity)); // true let str = "fatfish"; console.log(jsonstringify(str) === JSON.stringify(str)); // true let reg = new RegExp("\w"); console.log(jsonstringify(reg) === JSON.stringify(reg)); // true let date = new Date(); console.log(jsonstringify(date) === JSON.stringify(date)); // true let sym = Symbol('fatfish'); console.log(jsonstringify(sym) === JSON.stringify(sym)); // true let array = [1, 2, 3]; console.log(jsonstringify(array) === JSON.stringify(array)); // true let obj = { name: 'fatfish', age: 18, attr: ['coding', 123], date: new Date(), uni: Symbol(2), sayHi: function () { console.log("hello world") }, info: { age: 16, intro: { money: undefined, job: null } }, pakingObj: { boolean: new Boolean(false), string: new String('fatfish'), number: new Number(1), } } console.log(jsonstringify(obj) === JSON.stringify(obj)) // true console.log((jsonstringify(obj))) // {"name":"fatfish","age":18,"attr":["coding",123],"date":"2021-10-06T14:59:58.306Z","info":{"age":16,"intro":{"job":null}},"pakingObj":{"boolean":false,"string":"fatfish","number":1}} console.log(JSON.stringify(obj)) // {"name":"fatfish","age":18,"attr":["coding",123],"date":"2021-10-06T14:59:58.306Z","info":{"age":16,"intro":{"job":null}},"pakingObj":{"boolean":false,"string":"fatfish","number":1}}
          // 3. Test traversable objects let enumerableObj = {}
          Object.defineProperties(enumerableObj, { name: { value: 'fatfish', enumerable: true }, sex: { value: 'boy', enumerable: false }, })
          console.log(jsonstringify(enumerableObj)) // {"name":"fatfish"}
          // 4. Testing circular references and Bigint
          let obj1 = { a: 'aa' } let obj2 = { name: 'fatfish', a: obj1, b: obj1 } obj2.obj = obj2
          console.log(jsonstringify(obj2)) // TypeError: Converting circular structure to JSON console.log(jsonStringify(BigInt(1))) // TypeError: Do not know how to serialize a BigInt

          最后

          以上就是我今天跟你分享的全部?jī)?nèi)容,希望你能從今天的文章中學(xué)到新的知識(shí)。

          最后,感謝你的閱讀,祝編程愉快!



          學(xué)習(xí)更多技能

          請(qǐng)點(diǎn)擊下方公眾號(hào)

          aaf9698b728fdad433cee0b51b37d43b.webp

          76b3c6ca522ae8531a5f7604f4f3d496.webp

          瀏覽 53
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          評(píng)論
          圖片
          表情
          推薦
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  欧美疯狂做受XXXX猛交 | 水多多成人免费A片 | 天堂 在线8 | 靠逼视频免费观看 | 天堂网a|