js長整型的失真問題解決

遇到的問題:ios

  後端返回的訂單號是整型的,超過了Math.pow(2,53) = 9007199254740992,致使獲取的數據失真。json

  相似問題:https://www.zhihu.com/question/34564427axios

解決方法及思路:後端

  獲取到後端的數據以後,將json字符串獲取遍歷,大於 9007199254740992的數值轉爲字符串,具體方法以下:函數

/**
 * 由於js中的Json.parse()會讓Number數據類型精度丟失
 */
function getRealJsonData(baseStr) {
    if (!baseStr || typeof baseStr != 'string') return;
    var jsonData = null;
    try {
        jsonData = JSON.parse(baseStr);
    } catch (err) {
        return null;
    }
    var needReplaceStrs = [];
    loopFindArrOrObj(jsonData, needReplaceStrs);
    needReplaceStrs.forEach(function (replaceInfo) {
        var matchArr = baseStr.match('"' + replaceInfo.key + '":[0-9]{10,}');
        if (matchArr) {
            var str = matchArr[0];
            var replaceStr = str.replace('"' + replaceInfo.key + '":', '"' + replaceInfo.key + '":"');
            replaceStr += '"';
            baseStr = baseStr.replace(str, replaceStr);
        }
    });
    var returnJson = null;
    try {
        returnJson = JSON.parse(baseStr);
    } catch (err) {
        return null;
    }
    return returnJson;
}

/**
 * 遍歷對象類型的
 */
function getNeedRpStrByObj(obj, needReplaceStrs) {
    for (var key in obj) {
        var value = obj[key];
        // 大於這個數說明精度會丟失!
        if (typeof value == 'number' && value > 9007199254740992) {
            needReplaceStrs.push({ key: key });
        }
        loopFindArrOrObj(value, needReplaceStrs);
    }
}

/**
 * 判斷數據類型
 */
function getNeedRpStrByArr(arr, needReplaceStrs) {
    for (var i = 0; i < arr.length; i++) {
        var value = arr[i];
        loopFindArrOrObj(value, needReplaceStrs);
    }
}
/**
 * 遞歸遍歷
 */
function loopFindArrOrObj(value, needRpStrArr) {
    var valueTypeof = Object.prototype.toString.call(value);
    if (valueTypeof == '[object Object]') {
        needRpStrArr.concat(getNeedRpStrByObj(value, needRpStrArr));
    }
    if (valueTypeof == '[object Array]') {
        needRpStrArr.concat(getNeedRpStrByArr(value, needRpStrArr));
    }
}

上面是轉化的具體函數,接下來在返回數據的地方引用:oop

axios.post( url, data, {
    'X-Request-Form': 'XHR',
     headers: {
          'Authorization': 'Bearer ' + token
     },
     responseType: 'text',
     transformResponse: [function ( data ) {
          return getRealJsonData( data )
     }]
  } ).then( response => {
    console.log(response);
});
相關文章
相關標籤/搜索