首页 > 解决方案 > JS:TypeError:在对象中找不到功能键

问题描述

我在应用程序脚本中有以下内容:

function getQAs() {
    return [

      { "Do you have any pictures ?|1 ": {"yes":2,"no":3 } },
      { "Do you have any pictures ?|2 ": {"yes":2,"no":3 } },
      { "Do you have any pictures?|3 ": {"yes":2,"no":3 } },
    ]
}

我正在尝试构建一个函数,该函数将通过对象的键搜索数字。我正在使用数字 1 进行测试。当我运行时:

function testQA() {
  var qa = getQAs();
  var matches = qa.keys().filter(function(row) { //ONLY CHECKED ROWS.
    Logger.log(row)
    return row.indexOf('1') == true;
  });

  Logger.log(matches);
}

我明白了

JS:TypeError:在 object 中找不到功能键。我究竟做错了什么?

标签: javascriptgoogle-apps-script

解决方案


您需要使用for...in循环来获取对象的键。我设计了一个通过键的简单循环来确定键中是否存在值,然后推出一个过滤数组

function testQA() {
  var qa = getQAs();

  function getRow(row_identifier) {
  var filtered = [];
    qa.forEach(function(v) {
      for(var k in v) {
       if(k.indexOf(row_identifier) > 0) filtered.push(v);
      }
    });
         return filtered;
  }

   return getRow(row_identifier);
}

function getQAs() {
  return [

    {
      "Do you have any pictures ?|1 ": {
        "yes": 2,
        "no": 3
      }
    },
    {
      "Do you have any pictures ?|2 ": {
        "yes": 2,
        "no": 3
      }
    },
    {
      "Do you have any pictures?|3 ": {
        "yes": 2,
        "no": 3
      }
    },
  ]
}

function testQA() {
  var qa = getQAs();

  function getRow(row_identifier) {
  var filtered = [];
    qa.forEach(function(v) {
      for(var k in v) {
       if(k.indexOf(row_identifier) > 0) filtered.push(v);
      }
    });
         return filtered;
  }
      console.log(getRow(1));
      console.log(getRow(2))
      console.log(getRow(3))
}
testQA();


推荐阅读