-1

抱歉,我对 JS 很陌生,我正在尝试编写一些代码来动态计算页面上的单词,这段代码在“whenkeydown”函数中:

var text = $(this).val();

var word=text.split(" ")

    //word counter
function countWords(word, text) {
    var y = word.value; 
    var words = 0;
    a = y.replace(/\s/g, ' ');
    a = a.split(' ');
    for ( z = 0; z < a.length; z++) {
        if (a[z].length > 0)
            words++;
    }
    wordCount = words;
}

但是我在调​​试器中收到一条错误消息,说“TypeError:y is undefined”?谢谢

4

2 回答 2

4

word是一个数组,它没有属性value。此外,您的函数似乎接受整个字符串作为参数,而不是单词数组。这是一个更清晰的版本:

function countWords(text) {
    var words = text.replace(/\s/g, ' ').split(' ');
    var wordCount = 0;
    for (var z = 0; z < words.length; z++) {
        if (words[z].length > 0)
            wordCount++;
    }

    return wordCount;
}

var text = $(this).val();
var wordCount = countWords(text);
于 2012-11-20T12:33:24.247 回答
1
function countWords(wordsArray) {
  var words = 0;
  try{ 
    for(k in wordsArray){
      var sa = (wordsArray[k]  ? word.value.replace(/\s/g, ' ') : '').split(' ');
      for (i in sa) if(sa[i].trim()) words++;
    }
  catch(ex){}
  return words;
}

或者:

$(this).val().match(/\S+/g).length;
于 2012-11-20T12:36:02.197 回答