JavaScript - 首次运行时出错,第二次运行很好

时间:2016-04-16 00:09:34

标签: javascript jquery ajax

我有一个相当大的脚本,将在特定页面上从控制台执行 -

它基本上有3个部分

1)ajax请求从另一个页面获取HTML,然后从HTML中提取的所需数据创建数组

2)扫描所有单词的当前页面,忽略步骤1中的单词,创建包含所有未被忽略的单词的数组

3)在我弄清楚这个问题之后,还没有,但很简单

当我从控制台运行一次时,我得到:

Uncaught TypeError: Cannot read property 'length' of undefined(…)

如果我点击箭头然后再次输入并运行脚本,它将完全按照我的要求进入步骤1和2。

这是因为当第2步请求数组时,ajax请求没有完成吗?

var myFilter;
var dynamicExclude;
var arrDynamicExclude;
var staticExclude = ['are', 'is', 'where', 'was'];
var mergedExclude;
var words;
var word;
var ignore;
var finalList;

var stepOne = function () {
    //.unique
    Array.prototype.unique = function () {
        var a = this.concat();
        for (var i=0; i<a.length; ++i) {
            for(var j=i+1; j<a.length; ++j) {
                if(a[i] === a[j])
                    a.splice(j--, 1);
            }
        }
        return a;
    };
    // request HTML from wikipedia most common words
    $.ajax({
        url: 'https://en.wikipedia.org/wiki/Most_common_words_in_English',
        type: 'GET',
        dataType: 'html',
        success: function(data) {
                dynamicExclude = $.map($(data).find('.wikitable tr'), function(el, index) {
                return $(el).find('td:last').text() || null;
            });
            mergedExclude = dynamicExclude.concat(staticExclude).unique();
        }
    });
//->
    console.log("step 1");
}

var stepTwo = function () {
    // modified from: http://iamnotagoodartist.com/web/quick-and-dirty-word-frequency-analysis-with-javascript/
   var words = (function(){
        var sWords = document.body.innerText.toLowerCase().trim().replace(/[,;.]/g,'').split(/[\s\/]+/g).sort();
        // count w/ duplicates
        var iWordsCount = sWords.length;
        // array of words to ignore
        var ignore = mergedExclude;
        var ignore = (function(){
            // object prop checking > in array checking
            var o = {};
            var iCount = ignore.length;
            for (var i=0;i<iCount;i++){
                o[ignore[i]] = true;
            }
            return o;
        }());
        //do not allow words that are 1 chracter or non-alpha characters
        function myValidate(word) {
            return (word.length === 1 || /[^A-Z]/i.test(word)) ? true : false;
        }
        // object for math
        var counts ={};
        for (var i=0; i<iWordsCount; i++) {
            var sWord = sWords[i];
            if (!ignore[sWord] && !myValidate(sWord)) {
                counts[sWord] = counts[sWord] || 0;
                counts[sWord]++;
            }
        }
        // an array of objects to return
        var arr = [];
        for (sWord in counts) {
            arr.push({
                text: sWord,
                frequency: counts[sWord]
            });
        }
        // sort array by descending frequency | http://stackoverflow.com/a/8837505
        return arr.sort(function(a,b){
            return (a.frequency > b.frequency) ? -1 : ((a.frequency < b.frequency) ? 1 : 0);
        });
    }());
    (function(){
        // count w/o duplicates
        var iWordsCount = words.length;
        for (var i=0; i<iWordsCount; i++) {
            var word = words[i];
            //console.log(word.frequency, word.text);
        }
    }());
    var finalList =[];
    finalList = words.slice(0, 25);
    console.log(JSON.stringify(finalList));
//->
        console.log("step 2");
}

var stepThree = function(){
//->
        console.log("step 3");
}
//put the steps into the run queue
var runQueue = [stepOne,stepTwo,stepThree];
//run through the steps, removing the step from the queue after running
while (runQueue.length){
    runQueue.shift().call();
}

1 个答案:

答案 0 :(得分:0)

问题在于以下代码行:

dynamicExclude

您无法再访问成功功能之外的Uncaught TypeError: Cannot read property 'length' of undefined(…)

this

我剪了一行,然后记录了第1步中的内容。

图片作为证据:我所做的只是移除那条线......

enter image description here