使用数组中的第一个字符串查找未定义的内容

时间:2017-08-04 15:00:08

标签: javascript jquery

我正在做以下事情:

<p>1983 (on television), 1984 (in theatres)</p>

我跑

var d;
var dateText = $("p").text().split(/\s+/g);
for(var i = 0; i < dateText.length; i++) {
  d += dateText[i] + ' ';
}
var words = d.replace("–", " ").replace("-", " ").replace(",", " ").replace("/", " ").split(' ');
words = $.grep(words, function(n, i){
  return (n !== "" && n != null);
});
var array = words;
var newArray = array.filter(function(v){return v!==''});
console.log(newArray);
  

[&#34; undefined1983&#34;,&#34;(on&#34;,&#34; television)&#34;,&#34; 1984&#34;,&#34;(in&# 34;,&#34;剧院)&#34;]

我不应该undefined19831983

jsFiddle

如果我这样做:

var d;
var spacetime = [];
spacetime.push({
  Title : [],
  Space : [],
  Time : {
    days : [],
    months : [],
    years : [],
    suffixes : []
  },
  articleIdPush : [],
  originalFullDate : [],
  curArtLangPrefix : ["en"],
  SingleTranslatedArticle : [],
});
var dateText = $("p").text().split(/\s+/g);
for(var i = 0; i < dateText.length; i++) {
  d += dateText[i] + ' ';
}
var words = d.replace("–", " ").replace("-", " ").replace(",", " ").replace("/", " ").split(' ');
words = $.grep(words, function(n, i){
  return (n !== "" && n != null);
});
var array = words;
var newArray = array.filter(function(v){return v!==''});
for (const word of newArray) {
  if (months.has(word)) {
    spacetime[counter].Time.months.push(word);
  } else if (+word < 32) {
    spacetime[counter].Time.days.push(+word);
  } else if (+word < 2200) {
    spacetime[counter].Time.years.push(+word);
  } else if (/\w+/.test(word)) {
    spacetime[counter].Time.suffixes.push(word);
  }
}
console.log(spacetime);

我得到了

  

(index):90未捕获的ReferenceError:未定义月份

我应该在已定义的数组中包含正确的对象。

jsFiddle 2

1 个答案:

答案 0 :(得分:1)

问题在于:

link_to

对于循环的第一次迭代,您使用var d; d连接到自身,d +=未定义。当我指定d时,它按预期工作。

html5 attribute