PDA

View Full Version : Write a function that takes a string as an input and returns an array containing the



swathi
01-22-2008, 08:18 PM
Write a function that takes a string as an input and returns an array containing the odd words. With the string: "I can sing bad songs while in the shower", the output in the alert should read: "I sing songs in shower". Below is the basic framework that you should use.

<script type="text/javascript">
var allWords = "I can sing bad songs while in the shower";

function getOddWords(words){

//place code here

return oddWords;
}

alert(getOddWords(allWords));
</script>

Master_script_maker
01-22-2008, 08:32 PM
<script type="text/javascript">
var allWords = "I can sing bad songs while in the shower";

function getOddWords(words){

var oddWords = "";
var splitWords = words.split(" ");
var odd = true;
for (var i=0;i<splitWords.length;i=i+1) {
if (odd == true) {
oddWords += splitWords[i] + " ";
odd = false;
} else {
odd = true;
}
}

return oddWords;
}

alert(getOddWords(allWords));
</script>

swathi
01-22-2008, 08:51 PM
Take the function in above and create a String prototype so I can call the method using the following statement:

alert(allWords.getOddWords());

Master_script_maker
01-22-2008, 09:46 PM
String.prototype.oddwords = function() {
var oddWords = "";
var splitWords = this.split(" ");
var odd = true;
for (var i=0;i<splitWords.length;i=i+1) {
if (odd == true) {
oddWords += splitWords[i] + " ";
odd = false;
} else {
odd = true;
}
}

return oddWords;
}
you would use it like this:

var allWords = "I can sing bad songs while in the shower";
alert(allWords.oddwords());
and it would alert I sing songs in shower

ddadmin
01-22-2008, 11:31 PM
This sounds like a homework assignment. If so, please do not simply dump the entire assignment and expect someone else here to solve it for you. That's called cheating. You need to work on it yourself, and if you have a specific question on a particular aspect of the assignment, you're certainly welcome to get help on that.

I'll keep this thread open for now, but please be warned when starting new threads in the future.

Twey
01-23-2008, 01:04 AM
String.prototype.oddWords = function() {
for(var i = 0, w = this.split(" "), r = w && [w[0]]; i < w.length; ++i % 2 || w[i] && r.push(w[i]));
return r.join(" ");
};Agreed that it kind of sounds like a homework assignment though. Also note that this:
alert(getOddWords(allWords));this:
the output in the alert should read: "I sing songs in shower"and this:
returns an array containing the odd words... are mutually incompatible.