zoukankan      html  css  js  c++  java
  • javascript object 转换为 json格式 toJSONString

    Object.prototype.toJSONString = function () {
    
            var a = ['{'],  // The array holding the text fragments.
    
                b,          // A boolean indicating that a comma is required.
    
                k,          // The current key.
    
                v;          // The current value.
    
    
    
            function p(s) {
    
    
    
                // p accumulates text fragment pairs in an array. It inserts a comma before all
    
                // except the first fragment pair.
    
    
    
                if (b) {
    
                    a.push(',');
    
                }
    
                a.push(k.toJSONString(), ':', s);
    
                b = true;
    
            }
    
    
    
            // Iterate through all of the keys in the object, ignoring the proto chain.
    
    
    
            for (k in this) {
    
                if (this.hasOwnProperty(k)) {
    
                    v = this[k];
    
                    switch (typeof v) {
    
    
    
                    // Values without a JSON representation are ignored.
    
    
    
                    case 'undefined':
    
                    case 'function':
    
                    case 'unknown':
    
                        break;
    
    
    
                    // Serialize a JavaScript object value. Ignore objects that lack the
    
                    // toJSONString method. Due to a specification error in ECMAScript,
    
                    // typeof null is 'object', so watch out for that case.
    
    
    
                    case 'object':
    
                        if (this !== window)
    
                        {
    
                          if (v) {
    
                              if (typeof v.toJSONString === 'function') {
    
                                  p(v.toJSONString());
    
                              }
    
                          } else {
    
                              p("null");
    
                          }
    
                        }
    
                        break;
    
                    default:
    
                        p(v.toJSONString());
    
                    }
    
                }
    
            }
    
    
    
              // Join all of the fragments together and return.
    
    
    
            a.push('}');
    
            return a.join('');
    
        };
  • 相关阅读:
    Git fetch和git pull的区别
    git revert和git reset的区别
    JSF 与 HTML 标签的联系
    3. Decorator
    2. Observer
    1. Strategy
    继承构造函数的执行顺序
    模板特化
    8.1.2 Template instantiation (Accelerated C++)
    std::cin
  • 原文地址:https://www.cnblogs.com/EasonSun/p/2660288.html
Copyright © 2011-2022 走看看