1. 程式人生 > >使用foreach遍歷文章中出現所有單詞的次數

使用foreach遍歷文章中出現所有單詞的次數

var tweets = [
		    "Education is showing business the way by using technology to share information. How do we do so safely?",
		    "Enjoy a free muffin & coffee with Post Plus, our new loyalty club exclusive to subscribers!",
		    "We're LIVE on Periscope right now answering all your #pet questions - tweet us yours now!",
		    "Saw an unfinished print of M:I5 yesterday and it is my great pleasure to report it is rather splendid.",
		    "Downloading the beta of OS X El Capitan. This is going to gooch my mac for sure, but it will probably look pretty",
		    "Mud pies and muscle: H.G. Wells weighs in on #STEMeducation in an automated age",
		    "UK Space Agency brings astronaut’s mission to children across the UK #ESA #ESERO",
		    "Trying to find an old tweet that I didn't favourite at the time is…a fools game. #continuesDigging",
		    "A robot has just passed a classic test of self-awareness. What does that mean?",
		    "It was a great event. Very important to learn how to communicate about science and engineering effectively"
		];
		
		var words = {};
		//tweetText將陣列tweets中所有的元素轉化成以空格為分隔符的字串
		var tweetText = tweets.join(" ");
		//tweetWords將字串tweetText轉化成以空格為分隔符的陣列
		var tweetWords = tweetText.split(" ");
		
		//初始化讓所有陣列對應的次數為0
		//word是tweetWords陣列中的每一項的value值,用陣列的形式表現出來
		tweetWords.forEach(function (word) {
		    words[word] = 0;
		});
		
		//只要出現一次就加一
		
		tweetWords.forEach(function (word) {
		    words[word] = words[word] + 1;
		});
		
		console.log(words);

以此可以遍歷出各個字母出現的次數:


var tweets = [
  "Education is showing business the way by using technology to share information. How do we so so safely?",
  "Enjoy a free muffin & coffee with Post Plus, our new loyalty club exclusive to subscribers!",
  "We're LIVE on Periscope right now answering all your #pet questions - tweet us yours now!",
  "Saw an unfinished print of M:I5 yesterday and it is my great pleasure to report it is rather splendid.",
  "Downloading the beta of OS X El Capitan. This is going to gooch my mac for sure, but it will probably look pretty",
  "Mud pies and muscle: H.G. Wells weighs in on #STEMeducation in an automated age",
  "UK Space Agency brings astronaut’s mission to children across the UK #ESA #ESERO",
  "Trying to find an old tweet that I didn't favourite at the time is…a fools game. #continuesDigging",
  "A robot has just passed a classic test of self-awareness. What does that mean?",
  "It was a great event. Very important to learn how to communicate about science and engineering effectively"
];

var letters = {};
var tweetText = tweets.join("");
var tweetLetters = tweetText.split("");
  
tweetLetters.forEach(function (letter) {
    letters[letter.toLowerCase()] = 0;
});

tweetLetters.forEach(function (letter) {
    letters[letter.toLowerCase()] += 1;
});

console.log(letters);