Javascript 将字符串拆分为多维数组

Javascript 将字符串拆分为多维数组,javascript,object,Javascript,Object,我有一个字符串列表,我想检查字符串是否包含特定的单词,以及它是否拆分字符串中的所有单词并将其添加到关联数组中 myString = ['RT @Arsenal: Waiting for the international', 'We’re hungry for revenge @_nachomonreal on Saturday\'s match and aiming for a strong finish'] wordtoFind = ['@Arsenal'] 我想循环查找单

我有一个字符串列表,我想检查字符串是否包含特定的单词,以及它是否拆分字符串中的所有单词并将其添加到关联数组中

myString = ['RT @Arsenal: Waiting for the international', 'We’re hungry for revenge @_nachomonreal on Saturday\'s match and aiming for a strong finish']

wordtoFind = ['@Arsenal']       
我想循环查找
单词
,如果它在
myString
中,则将
myString
拆分为单个单词,并创建一个类似

newWord = {@Arsenal:[{RT:1},{Waiting:1},{for:1},{the:1},{international:1}]}

for(z=0; z <wordtoFind.length; z++){
  for ( i = 0 ; i < myString.length; i++) {
    if (myString[i].indexOf(wordtoFind[z].key) > -1){
      myString[i].split(" ")
    }
  }
}
newWord={@Arsenal:[{RT:1},{Waiting:1},{for:1},{the:1},{international:1}]}
对于(z=0;z-1){
myString[i]。拆分(“”)
}
}
}

你走对了方向。您只需要将拆分的字符串存储到关联数组变量中

var assocArr = [];
for(z=0; z <wordtoFind.length; z++){
     for ( i = 0 ; i < myString.length; i++) {
         if (myString[i].indexOf(wordtoFind[z]) > -1){

             myString[i].split(" ").forEach(function(word){
                 assocArr.push(word);
             });

         }
     }
}
var-assocar=[];
对于(z=0;z-1){
myString[i].split(“”).forEach(函数(word){
助推(字);
});
}
}
}

你走对了方向。您只需要将拆分的字符串存储到关联数组变量中

var assocArr = [];
for(z=0; z <wordtoFind.length; z++){
     for ( i = 0 ; i < myString.length; i++) {
         if (myString[i].indexOf(wordtoFind[z]) > -1){

             myString[i].split(" ").forEach(function(word){
                 assocArr.push(word);
             });

         }
     }
}
var-assocar=[];
对于(z=0;z-1){
myString[i].split(“”).forEach(函数(word){
助推(字);
});
}
}
}

我想说,类似的东西会起作用,这也会计算一个单词在一个句子中出现的次数。JavaScript没有像PHP这样的关联数组。它们只有
对象
或编号的
数组

var myString = ['RT @Arsenal: Waiting for the international', 'We’re hungry for revenge @_nachomonreal on Saturday\'s match and aiming for a strong finish'];

var wordtoFind = ['@Arsenal'];

var result = {};

for(var i = 0, l = wordtoFind.length; i < l; i++) {

    for(var ii = 0, ll = myString.length; ii < ll; ii++) {
        if(myString[ii].indexOf(wordtoFind[i]) !== -1) {
            var split = myString[ii].split(' ');
            var resultpart = {};
            for(var iii = 0, lll = split.length; iii < lll; iii++) {
                if(split[iii] !== wordtoFind[i]) {
                    if(!resultpart.hasOwnProperty(split[iii])) {
                      resultpart[split[iii]] = 0;
                    }
                    resultpart[split[iii]]++;
                }
            }
            result[wordtoFind[i]] = resultpart;
        }
    }
}

console.log(result); 
//{"@Arsenal":{"RT":1,"Waiting":1,"for":1,"the":1,"international":1}}
var myString=['RT@阿森纳:等待国际米兰”,“我们渴望在周六的比赛中复仇,并希望有一个强劲的终点];
var wordtoFind=['@Arsenal'];
var result={};
for(var i=0,l=wordtoFind.length;i
我想说,类似的东西会起作用,这也会计算一个单词在一个句子中出现的次数。JavaScript没有像PHP这样的关联数组。它们只有
对象
或编号的
数组

var myString = ['RT @Arsenal: Waiting for the international', 'We’re hungry for revenge @_nachomonreal on Saturday\'s match and aiming for a strong finish'];

var wordtoFind = ['@Arsenal'];

var result = {};

for(var i = 0, l = wordtoFind.length; i < l; i++) {

    for(var ii = 0, ll = myString.length; ii < ll; ii++) {
        if(myString[ii].indexOf(wordtoFind[i]) !== -1) {
            var split = myString[ii].split(' ');
            var resultpart = {};
            for(var iii = 0, lll = split.length; iii < lll; iii++) {
                if(split[iii] !== wordtoFind[i]) {
                    if(!resultpart.hasOwnProperty(split[iii])) {
                      resultpart[split[iii]] = 0;
                    }
                    resultpart[split[iii]]++;
                }
            }
            result[wordtoFind[i]] = resultpart;
        }
    }
}

console.log(result); 
//{"@Arsenal":{"RT":1,"Waiting":1,"for":1,"the":1,"international":1}}
var myString=['RT@阿森纳:等待国际米兰”,“我们渴望在周六的比赛中复仇,并希望有一个强劲的终点];
var wordtoFind=['@Arsenal'];
var result={};
for(var i=0,l=wordtoFind.length;i
我认为困扰您的关键问题是数据结构。最佳结构应如下所示:

{
    @Arsenal:[
        {RT:1, Waiting:1, for:1, the:1, international:1},
        {xxx:1, yyy:1, zzz:3}, //for there are multiple ones in 'myString' that contain the same '@Arsenal'
        {slkj:1, sldjfl:2, lsdkjf:1} //maybe more
    ]
    someOtherWord:[
        {},
        {},
        ....
    ]
}
以及守则:

var result = {};

//This function will return an object like {RT:1, Waiting:1, for:1, the:1, international:1}.
function calculateCount(string, key) {
    var wordCounts = {};
    string.split(" ").forEach(function (word) {
        if (word !== key) {
            if (wordCounts[word] === undefined) wordCounts[word] = 1;
            else wordCounts[word]++;
        }
    });
    return wordCounts;
}

//For each 'word to find' and each string that contain the 'word to find', push in that returned object {RT:1, Waiting:1, for:1, the:1, international:1}.
wordToFind.forEach(function (word) {
    var current = result[word] = [];
    myString.forEach(function (str) {
        if (str.indexOf(word) > -1) {
            current.push(
                calculateCount(str, word)
            );
        }
    });  //Missed the right parenthesis here
});

我认为困扰你的关键问题是数据结构。最佳结构应如下所示:

{
    @Arsenal:[
        {RT:1, Waiting:1, for:1, the:1, international:1},
        {xxx:1, yyy:1, zzz:3}, //for there are multiple ones in 'myString' that contain the same '@Arsenal'
        {slkj:1, sldjfl:2, lsdkjf:1} //maybe more
    ]
    someOtherWord:[
        {},
        {},
        ....
    ]
}
以及守则:

var result = {};

//This function will return an object like {RT:1, Waiting:1, for:1, the:1, international:1}.
function calculateCount(string, key) {
    var wordCounts = {};
    string.split(" ").forEach(function (word) {
        if (word !== key) {
            if (wordCounts[word] === undefined) wordCounts[word] = 1;
            else wordCounts[word]++;
        }
    });
    return wordCounts;
}

//For each 'word to find' and each string that contain the 'word to find', push in that returned object {RT:1, Waiting:1, for:1, the:1, international:1}.
wordToFind.forEach(function (word) {
    var current = result[word] = [];
    myString.forEach(function (str) {
        if (str.indexOf(word) > -1) {
            current.push(
                calculateCount(str, word)
            );
        }
    });  //Missed the right parenthesis here
});

此方法使用-函数和回调。 containsWord函数现在留下了一个for循环,以减少一些回调,这显然是可以改变的

var myString = [
    'RT @Arsenal: Waiting for the international',
    'We’re hungry for revenge @_nachomonreal on Saturday\'s match and aiming for a strong finish',
    '@Arsenal: one two three four two four three four three four'
];

var wordtoFind = ['@Arsenal'];

// define the preprocessor that is used before the equality check
function preprocessor(word) {
    return word.replace(':', '');
}

function findOccurences(array, search, callback, preprocessor) {
    var result = {};
    var count = 0;
    // calculate the maximum iterations
    var max = search.length * array.length;
    // iterate the search strings that should be matched
    search.forEach(function(needle) {
        // iterate the array of strings that should be searched in
        array.forEach(function(haystack) {
            if (containsWord(haystack, needle, preprocessor)) {
                var words = haystack.split(' ');
                // iterate every word to count the occurences and write them to the result
                words.forEach(function(word) {
                    countOccurence(result, needle, word);
                })
            }
            count++;
            // once every iteration finished, call the callback
            if (count == max) {
                callback && callback(result);
            }
        });
    });
}

function containsWord(haystack, needle, preprocessor) {
    var words = haystack.split(' ');
    for (var i = 0; i < words.length; i++) {
        var word = words[i];
        // preprocess a word before it's compared
        if (preprocessor) {
            word = preprocessor(word);
        }
        // if it matches return true
        if (word === needle) {
            return true;
        }
    }
    return false;
}

function countOccurence(result, key, word) {
    // add array to object if it doesn't exist yet
    if (!result.hasOwnProperty(key)) {
        result[key] = [];
    }
    var entry = result[key];
    // set the count to 0 if it doesn't exist yet
    if (!entry.hasOwnProperty(word)) {
        entry[word] = 0;
    }
    entry[word]++;
}

// call our function to find the occurences
findOccurences(myString, wordtoFind, function(result) {
    // do something with the result
    console.log(result);
}, preprocessor);

// output:
/*
 { '@Arsenal':
   [ RT: 1,
    '@Arsenal:': 2,
    Waiting: 1,
    for: 1,
    the: 1,
    international: 1,
    one: 1,
    two: 2,
    three: 3,
    four: 4 ] }
 */
var myString=[
“RT@Arsenal:等待国际比赛”,
“我们渴望在周六的比赛中复仇,并希望有一个强劲的终点。”,
“@阿森纳:一二三四二四三四四”
];
var wordtoFind=['@Arsenal'];
//定义在相等性检查之前使用的预处理器
函数预处理器(word){
返回单词。替换(':','');
}
函数findOccurences(数组、搜索、回调、预处理器){
var result={};
var计数=0;
//计算最大迭代次数
var max=search.length*array.length;
//迭代应该匹配的搜索字符串
search.forEach(功能(针){
//迭代应在中搜索的字符串数组
array.forEach(函数(haystack){
if(干草堆、针、预处理器){
var words=haystack.split(“”);
//迭代每个单词以计算出现次数并将其写入结果
words.forEach(函数(word){
计数发生(结果、针、字);
})
}
计数++;
//每次迭代完成后,调用回调函数
如果(计数=最大值){
回调&回调(结果);
}
});
});
}
功能(草堆、针、预处理器){
var words=haystack.split(“”);
for(var i=0;i