无法推入多维数组

时间:2018-07-26 03:34:51

标签: javascript

我正在尝试在数组的第二列中推送一个计数器,但是它不起作用。我究竟做错了什么? 我的问题出在功能“ matchKeywords” ,特别是行arrayToMatch[i].push(counter);

这是我得到的错误:

Uncaught TypeError: arrayToMatch[i].push is not a function
at matchKeywords ((index):54)
at window.onload ((index):73)

这是我的代码:

var arrayOfKeywords = ['USA Canada UK Australia Japan India', 'USA Canada UK India UK Australia China Brazil France', 'Brazil France Australia China'];
var oneWord = [[]];
var twoWords = [[]];
var threeWords = [[]];
var ArrayOneWords = arrayOfKeywords.join(" ").split(" ");

for(i = 2; i < ArrayOneWords.length -1; i++){
    //Create array twoWords
    twoWords.push(ArrayOneWords[i-2] + " " + ArrayOneWords[i-1]);
  //Create array threeWords
    threeWords.push(ArrayOneWords[i-2] + " " + ArrayOneWords[i-1] + " " + ArrayOneWords[i]);  
}

function matchKeywords(arraySource, arrayToMatch){
var counter = 0;
    for(i = 0; i < arrayToMatch.length; i++){
    counter = 0;
    for(j = 0; j < arraySource.length; j++){
        if (arraySource[j].indexOf(arrayToMatch[i]) >= 0){
        counter++;
        }
    }
    arrayToMatch[i].push(counter);
    }
}

//Remove duplicate
function unique(list) {
    var result = [];
    $.each(list, function(i, e) {
        if ($.inArray(e, result) == -1) result.push(e);
    });
    return result;
}

oneWord = unique(oneWord);
twoWords = unique(twoWords);
threeWords = unique(threeWords);

console.table(matchKeywords(arrayOfKeywords, twoWords));

2 个答案:

答案 0 :(得分:0)

您遇到的问题是,在osmosis .get("https://somesite.com") .find("#login- form").login("mailid","password","login sucess","login failed") .set({ div: 'div', title: 'title' }) .log(console.log) .debug(console.log) .error(console.log); 函数中,您将matchKeywords()视为锯齿状数组(数组的数组)-但是您要将该数组传递给函数( arrayToPush)只是一个常规的一维数组。

您最初将其定义为twoWords的确确实创建了一个锯齿状的数组,但是对var twoWords = [[]];的调用将其转换为一维数组。

这就是为什么您看到错误消息“ twoWords = unique(twoWords);”的原因-因为现在存储在arrayToMatch[i].push is not a function的内容不再是数组-因为调用了arrayToMatch[i]

答案 1 :(得分:0)

由于定义了var twoWords = [[]];,因此出现错误。因此twoWords是多维数组,但内部只有一个数组。因此,对于twoWords[1],它将是undefined

更新matchKeywords功能如下。添加了一行arrayToMatch[i] = arrayToMatch[i] || [];

function matchKeywords(arraySource, arrayToMatch) {
    var counter = 0;
    for(i = 0; i < arrayToMatch.length; i++) {
        counter = 0;
        for(j = 0; j < arraySource.length; j++){
            if (arraySource[j].indexOf(arrayToMatch[i]) >= 0) {
                counter++;
            }
        }
        arrayToMatch[i] = arrayToMatch[i] || [];
        arrayToMatch[i].push(counter);
    }
}