2017-08-04 27 views
-2

我做了以下内容:找到一个数组中与第一串未定义

<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); 

["undefined1983", "(on", "television)", "1984", "(in", "theatres)"]

我不应该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 Uncaught ReferenceError: months is not defined

我应该有它正确的对象定义的数组。

jsFiddle 2

+0

您期待的输出是什么? – abagshaw

+2

我不明白是什么问题?你想摆脱'undefined'吗?你想知道它为什么在那里? –

+0

@ N.Ivanov对不起刚刚更新,因为我包括第二个问题,但情况是类似的 –

回答

1

的问题是有:

var d; 

对于你的循环的第一次迭代,其中您连接到d本身d +=d是不确定的。当我指定var d = '';时,它按预期工作。

Here's the working jsFiddle

相关问题