题目:编写一个函数,接受一个字符串作为参数,统计该字符串中每个单词出现的次数,并返回一个对象,对象的属性为单词,属性值为该单词出现的次数。注意,单词不区分大小写,需要忽略标点符号和空格。

示例输入:"This is a test. This is only a test." 示例输出:{this: 2, is: 2, a: 2, test: 2, only: 1}

答案:

function countWords(str) { // 将字符串转换为小写,并去除标点符号和空格 str = str.toLowerCase().replace(/[^\w\s]/g, '').replace(/\s+/g, ' '); // 将字符串转换为数组 var arr = str.split(' '); // 创建一个空对象 var obj = {}; // 遍历数组,统计单词出现次数 for (var i = 0; i < arr.length; i++) { var word = arr[i]; if (obj[word]) { obj[word]++; } else { obj[word] = 1; } } return obj; }

console.log(countWords("This is a test. This is only a test.")); // 输出:{this: 2, is: 2, a: 2, test: 2, only: 1}

出一道困难难度的js编程题并给出答案

原文地址: http://www.cveoy.top/t/topic/L0Z 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录