当前位置:Gxlcms > JavaScript > javascript遍历json对象的key和任意js对象属性实例

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

时间:2021-07-01 10:21:17 帮助过:5人阅读

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

  1. function Pasta(grain, width, shape) {
  2. this.grain = grain;
  3. this.width = width;
  4. this.shape = shape;
  5. this.toString = function () {
  6. return (this.grain + ", " + this.width + ", " + this.shape);
  7. }
  8. }
  9. var spaghetti = new Pasta("wheat", 0.2, "circle");
  10. var arr = Object.keys(spaghetti);
  11. document.write(arr);

结果图:

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

  1. function Pasta(grain, width, shape) {
  2. this.grain = grain;
  3. this.width = width;
  4. this.shape = shape;
  5. }
  6. function CheckKey(value) {
  7. var firstChar = value.substr(0, 1);
  8. if (firstChar.toLowerCase() == "g") {
  9. return true;
  10. } else {
  11. return false;
  12. }
  13. }
  14. var polenta = new Pasta("corn", 1, "mush");
  15. var keys = Object.keys(polenta).filter(CheckKey);
  16. document.write(keys);

结果如图:

遍历json对象的键:

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

结果如图:


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

人气教程排行