当前位置: 移动技术网 > IT编程>开发语言>JavaScript > javascript遍历json对象的key和任意js对象属性实例

javascript遍历json对象的key和任意js对象属性实例

2019年06月11日  | 移动技术网IT编程  | 我要评论
使用 keys 方法获取该对象的属性和方法: function pasta(grain, width, shape) { this.grain

使用 keys 方法获取该对象的属性和方法:

 function pasta(grain, width, shape) {
        this.grain = grain;
        this.width = width;
        this.shape = shape;
        this.tostring = function () {
          return (this.grain + ", " + this.width + ", " + this.shape);
        }
      }
      
      var spaghetti = new pasta("wheat", 0.2, "circle");
      var arr = object.keys(spaghetti);
      document.write(arr);

结果图:

显示 pasta 对象中以字母“g”开头的所有可枚举属性的名称:

function pasta(grain, width, shape) {
        this.grain = grain;
        this.width = width;
        this.shape = shape;
      }

      function checkkey(value) {
        var firstchar = value.substr(0, 1);
        if (firstchar.tolowercase() == "g") {
          return true;
        } else {
          return false;
        }
      }

      var polenta = new pasta("corn", 1, "mush");
      var keys = object.keys(polenta).filter(checkkey);
      document.write(keys);

结果如图:

遍历json对象的键:

var an_obj = { 100: 'a', 2: 'b', 7: 'c', "name": "wu", "interesting": "game" };
 document.write(object.keys(an_obj));

结果如图:


以上这篇javascript遍历json对象的key和任意js对象属性实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网