在Google Apps脚本中循环播放数组

时间:2014-05-30 00:48:06

标签: javascript arrays loops google-apps-script

我正在尝试为数组编写一个循环但是收到无效的字符串错误。

如果keyword =“mesothelioma | seo”

function json(keyword) {
  var jsondata = UrlFetchApp.fetch("http://api.grepwords.com/lookup?apikey=carterq="+keyword);
  var object = Utilities.jsonParse(jsondata.getContentText());

  var results = Array("Error", "Error", "Error", "Error");

  for (var i = 0; i < object.length; i++) {

  results[0] = object[0].cpc;
  results[1] = object[0].cmp;
  results[2] = object[0].lms;
  results[3] = object[0].m1;
  }

  return results;
}

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您的参考错误来自这一行:

var jsondata = UrlFetchApp.fetch("http://api.grepwords.com/lookup?apikey=carter&q="+keyword);

从上面的代码中,这是您使用&#39;关键字&#39;的唯一时刻。您确定它会返回正确的信息吗?如果它确实让你考虑过你的循环?

假设您的var object = Utilities.jsonParse(jsondata.getContentText());返回此信息:

  var object = [
      {cpc: 'test1', cmp: 'test2', lms: 'test3', m1: 'test4'},
      {cpc: 'test5', cmp: 'test6', lms: 'test7', m1: 'test8'},
      {cpc: 'test9', cmp: 'test10', lms: 'test11', m1: 'test12'}
  ];

我们使用你的循环:

  for (var i = 0; i < object.length; i++) {

  results[0] = object[0].cpc;
  results[1] = object[0].cmp;
  results[2] = object[0].lms;
  results[3] = object[0].m1;
  }

你确实意识到你永远不会使用&#39;我&#39;?你在每次循环后用同样的东西覆盖结果中的内容吗?你确定要这个吗?

&#13;
&#13;
function somefunc() {

  var object = [
      {cpc: 'test1', cmp: 'test2', lms: 'test3', m1: 'test4'},
      {cpc: 'test5', cmp: 'test6', lms: 'test7', m1: 'test8'},
      {cpc: 'test9', cmp: 'test10', lms: 'test11', m1: 'test12'}
  ];
  var results = Array("Error", "Error", "Error", "Error");

  if (object[0] != undefined)
  {
  results[0] = object[0].cpc;
  results[1] = object[0].cmp;
  results[2] = object[0].lms;
  results[3] = object[0].m1;
  }

  for (var i = 0; i < object.length; i++) {

  results[0] = object[0].cpc;
  results[1] = object[0].cmp;
  results[2] = object[0].lms;
  results[3] = object[0].m1;
  }

  return results;
}

console.log(somefunc());
&#13;
&#13;
&#13;