我试图计算某些单词出现在字符串中的次数。每次我运行它都会得到一个
未捕获TypeErro:undefined不是函数
我实际上需要计算每个" major"出现。
以下是我的代码:
for(var i = 0; i < sortedarray.length; i++)
{
if(sortedarray.search("Multimedia") === true)
{
multimedia += 1;
}
}
console.log(multimedia);
这是我的csv文件,它存储在1d数组中。
"NAME","MAJOR","CLASS STANDING","ENROLLMENT STATUS"
"Smith, John A","Computer Science","Senior","E"
"Johnson, Brenda B","Computer Science","Senior","E"
"Green, Daisy L","Information Technology","Senior","E"
"Wilson, Don A","Information Technology","Junior","W"
"Brown, Jack J","Multimedia","Senior","E"
"Schultz, Doug A","Network Administration","Junior","E"
"Webber, Justin","Business Administration","Senior","E"
"Alexander, Debbie B","Multimedia","Senior","E"
"St. John, Susan G","Information Technology","Junior","D"
"Finklestein, Harold W","Multimedia","Freshman","E"
答案 0 :(得分:2)
你可能要做的是:
for(var i = 0; i < sortedarray.length; i++)
{
if(sortedarray[i].indexOf("Multimedia") !== -1)
{
multimedia++;
}
}
console.log(multimedia);
我使用indexOf
,因为如果你没有使用正则表达式,search
有点矫枉过正。
另外,我将+= 1
替换为++
。它实际上是一样的。
答案 1 :(得分:2)
您需要在每个字符串内搜索而不是数组。要仅在“主要”列中搜索,您可以在索引1处开始循环并增加4:
var multimedia = 0;
for(var i = 1; i < sortedarray.length; i += 4)
{
if(sortedarray[i].indexOf("Multimedia") > -1)
{
multimedia += 1;
}
}
console.log(multimedia);
答案 2 :(得分:1)
这是一个更直接的解决方案。首先使用reduce计算所有单词,然后您可以使用点表示法访问它们(如果您有字符串或动态值,则可以使用括号表示法):
var words = ["NAME","MAJOR","CLASS STANDING","ENROLLMENT STATUS"...]
var count = function(xs) {
return xs.reduce(function(acc, x) {
// If a word already appeared, increment count by one
// otherwise initialize count to one
acc[x] = ++acc[x] || 1
return acc
},{}) // an object to accumulate the results
}
var counted = count(words)
// dot notation
counted.Multimedia //=> 3
// bracket notation
counted['Information Technology'] //=> 3
答案 3 :(得分:0)
我不确切地知道你是否需要这个。但我认为最好在单循环中计算每个单词的出现次数如下:
var occurencesOfWords = {};
for(var i = 0; i < sortedarray.length; i++)
{
var noOfOccurences = (occurencesOfWords[sortedarray[i]]==undefined?
1 : ++occurencesOfWords[sortedarray[i]]);
occurencesOfWords[sortedarray[i]] = noOfOccurences;
}
console.log(JSON.stringify(occurencesOfWords));
所以你最终会得到这样的东西:
{"Multimedia":3,"XYZ":2}
答案 4 :(得分:-1)
.search
为undefined
,并且不在数组上function
。
但是你想检查的当前string
上存在!只需使用string
选择数组中的当前sortedarray[i]
。
修复你的代码:
for(var i = 0; i < sortedarray.length; i++)
{
if(sortedarray[i].search("Multimedia") === true)
{
multimedia += 1;
}
}
console.log(multimedia);