I wrote a function to count the length and vowels in a word and output them in objects in an array. Yet I get the error "word.match() is not a function" where word is a string.
function wordData(string){
var stringSplit = string.split(' ');
var output = [];
for(var i = 0; i <= stringSplit.length; i++){
var eachWord = stringSplit[i];
var vowel = eachWord.match(/[aeiou]/gi);
var vowelCount = vowel ? vowel.length : 0;
var objectData = {};
objectData.word = eachWord;
objectData.length = eachWord.length;
objectData.vowels = vowelCount;
output.push(objectData);
}
return output;
}
console.log(wordData('some really awesome string'));
any idea what is wrong?
for(var i = 0; i <= stringSplit.length; i++)
That'll go up past the last index of your array of strings. Therefore, it will be undefined, and you can't call match on undefined.
Do this instead:
for(var i = 0; i < stringSplit.length; i++)
Index out of bounds
for(var i = 0; i <= stringSplit.length; i++){
should be
for(var i = 0; i < stringSplit.length; i++){
Related
I am trying to generate a random words and push each one individually to the array, the problem is, i am getting list of words that starts from the first letter increased by one like this:
['a','ab','abc','abcd'] and so on
here is my code:
var word = "";
var texts = [];
var letters = "абвгдеёжзийклмнопрстуфхцчшщъыьэюя";
for (var i = 0; i < 10; i++){
word += letters.charAt(Math.floor(Math.random() * letters.length))
texts.push(
{
"id":i,
"name":word,
selected: false
}
)
}
what i need is to push a complete word to the list.
var texts = [];
var letters = "абвгдеёжзийклмнопрстуфхцчшщъыьэюя";
var wordLength = 5;
for (var i = 0; i < 10; i++){
let word = "";
for(var j = 0; j < wordLength; j++) {
word += letters.charAt(Math.floor(Math.random() * letters.length));
}
texts.push(
{
"id": i,
"name": word,
selected: false
}
)
}
You need to use another one loop for generate a words. New word's loop each time.
var word = "";
var texts = [];
var letters = "abcdefghijklmn";
for (var i = 0; i < 10; i++){
word = letters.slice(1,i)
texts.push(word);
}
alert(texts);
Oh, sorry you need it random;
how about this
var word = "";
var texts = [];
var letters = "abcdefghijklmn";
var l = letters.length;
var textsNum = 10;
for (var v = 0; v < textsNum; v++) {
for (var i = 0; i < l; i++) {
word += letters[Math.floor(Math.random() * l)];
}
texts.push(word);
word = '';
}
console.dir(texts);
I want to do the following:
The string 'London' needs to be printed acording to this logic:
'L'
'Lo'
'Lon'
'Lond'
'Londo'
'London'
An array or loop is what I have in mind, but a can't get it right. Someone who can help?
A simple loop would do it.
Use Array.prototype.slice (https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/slice) to get the wanted portion of the string.
const string = 'London';
for (let i = 0; i < string.length; i++) {
console.log(string.slice(0,i+1));
}
A easy way of using substring method.
const str = "LONDON";
for (let i =0; i<= str.length ;){
console.log(str.substring(0,i++));
}
You may found it strange with using i <= str.length because str.substring(0,0) return empty string "",
You can change to :
const str = "LONDON";
for (let i =0; i< str.length ;){
console.log(str.substring(0,++i));
}
You could use two for loops. One to iterate through all the positions of "London", and the other to iterate through portions of the word "London". Take a look at the code snippet bellow:
var word = "London";
for (var i = 0; i < word.length; i++) {
var str = "";
for (var j = 0; j <= i; j++) {
str += word[j];
}
console.log(str);
}
Below code will be work fine for your problem.
var a = "LONDON";
a = a.split('');
var str = '';
for (var i = 0; i < a.length; i++) {
str += a[i];
console.log(str);
}
Happy Coding!!
I have this so far, trying to get it to find the sum of each one of any number of inputted numbers with integers and "-"s.
When I run this,
var howM = prompt("How many cards?")
var arr = [];
for (var i = 0; i < howM; i++)
arr.push(prompt("Enter a card:"));
console.log(arr)
var sumpre = [];
for (var i = 0; i <= howM; i++) {
var sum = 0;
var eXt = arr[i];
eXt = eXt.replace(/-/g, "");
for (i = 0; i < eXt.length; i++) {
sum += parseInt(eXt.substr(i, 1));
}
sumpre.push(sum);
}
console.log(sumpre)
I have also tried
var howM = prompt("How many cards?")
var arr = [];
for (var i = 0; i < howM; i++)
arr.push(prompt("Enter a card:"));
console.log(arr)
for (var i = 0; i < howM; i++) {
var sum = 0;
var eXt = arr[i]
eXt = eXt.replace(/-/g, "");
for (i = 0; i < eXt.length; i++) {
sum += parseInt(eXt.substr(i, 1));
}
}
console.log(sum);
In both cases I get the sum for the first piece in the array and then undefined. How do I get it to run for each piece? I kind of have an idea of what is wrong with it I just don't quite know how to fix it.
You need to use a second counter for the nested for loop, like so:
var howM = prompt("How many cards?")
var arr = [];
for(var i = 0; i < howM; i++)
arr.push(prompt("Enter a card:"));
console.log(arr)
var sumpre = [];
for(var i = 0; i < howM; i++) {
var sum = 0;
var eXt = arr[i];
eXt = eXt.replace (/-/g, "");
for (var j = 0; j < eXt.length; j++) {
sum += parseInt(eXt.substr(j, 1));
}
sumpre.push(sum);
}
console.log(sumpre)
Your var sum = 0; inside your for-loop meaning sum variable will not be accessible outside of the loop
var howM = prompt("How many cards?")
var arr = [];
for(var i = 0; i < howM; i++)
arr.push(prompt("Enter a card:"));
console.log(arr)
for(var i = 0; i <= howM; i++)
var sum = 0;
var eXt = arr[i]
eXt = eXt.replace (/-/g, "");
for (i = 0; i < eXt.length; i++) {
sum += parseInt(eXt.substr(i, 1)); }
console.log(sum);
It tells me this "TypeError: Cannot read property 'replace' of undefined
at eval:13:11" which makes no sense to me because its right above it.
The intetended body of the loop for(var i = 0; i <= howM; i++) is not enclosed in braces {..}. As a result, only the statement var sum = 0; will be executed in the loop. Also, you probably meant to say i < howM. So you want something like this for the loop:
for(var i = 0; i < howM; i++) {
var sum = 0;
var eXt = arr[i]
eXt = eXt.replace (/-/g, "");
for (i = 0; i < eXt.length; i++) {
sum += parseInt(eXt.substr(i, 1));
}
}
console.log(sum);
Check the comments:
var howM = prompt("How many cards?")
var arr = [];
for(var i = 0; i < parseInt(howM); i++)
arr.push(prompt("Enter a card:")); //No curly braces is fine when its a single line. When there's no braces, JS just runs the next line x amount of times
console.log(arr)
var sum = 0; //Create sum out here. Setting it to zero every loop defeats the purpose
for(var i = 0; i < arr.length; i++)//You said "i <= howM". Better to use the length of the array that is being looped through
{ //Use curly braces to show what code to execute repeatedly
var eXt = arr[i]; //Set eXt to the current number
eXt = eXt.replace("-", ""); //No need for regex
sum += parseInt(eXt); //Convert the input to a number, then add it to sum
}
console.log(sum);
The second for loop doesn't have brackets around it. You can MUST use brackets UNLESS it is a one line loop. For example:
This is fine:
for (var i=0;i<100;i++)
console.log(i);
This is NOT:
for (var i=0;i<100;i++)
var x = i;
x++;
console.log(x);
So the second for loop should be this:
for(var i = 0; i <= howM; i++) {
var sum = 0;
var eXt = arr[i]
eXt = eXt.replace (/-/g, "");
for (i = 0; i < eXt.length; i++) {
sum += parseInt(eXt.substr(i, 1));
}
console.log(sum);
}
Also in the first for loop I would use arr[i] = value instead.
Can I use variable to do the second for loop so it list out all data in GroupA1 and GroupB1.
Tried but fail.. anyone have idea how to make it work?
for example
function Loop(){
var AllGroup=["GroupA1","GroupB1"]
var GroupA1=["A1","A2"]
var GroupB1=["B1","B2"]
var Group=""
for(var i = 0; i < AllGroup.length; i++){
Group=AllGroup[i]
var SubGroup=""
for(var x = 0; x < Group.length; x++){
SubGroup=Group[x]
alert(SubGroup);
}
}
}
Hopefully my sample code can help you to deal with your question
For example
<script>
var GroupA1=["A1","A2"]
var GroupB1=["B1","B2"]
var Group=""
var AllGroup = [GroupA1, GroupB1]
for(var i = 0; i < AllGroup.length; i++){
Group=AllGroup[i]
var SubGroup=""
for(var x = 0; x < Group.length; x++){
SubGroup=Group[x]
alert(SubGroup);
}
}
</script>
Do it this way:
function loop(){
var GroupA1=["A1","A2"]
var GroupB1=["B1","B2"]
var AllGroup=[GroupA1,GroupB1]
var Group=""
for(var i = 0; i < AllGroup.length; i++){
Group=AllGroup[i]
var SubGroup=""
for(var x = 0; x < Group.length; x++){
SubGroup=Group[x]
alert(SubGroup);
}
}
}
Declare the arrays first then use them as objects in the next array.
This is the structure I would recommend, which is more logical, instead of what you're using.
function Loop(){
//The object AllGroups contains all the other groups
var AllGroups = {
"GroupA1": ["A1","A2"],
"GroupB1": ["B1","B2"]
};
for(var group in AllGroups){
if(AllGroups.hasOwnProperty(group)){
//Access each group in AllGroups
for(var i = 0; i < AllGroups[group].length; i++){
console.log(AllGroups[group][i]); //A1, A2, B1, B2
}
}
}
}
Rearrange code like this so that AllGroup is a collection containing GroupA1 and GroupB1:
function Loop() {
var GroupA1=["A1", "A2"];
var GroupB1=["B1", "B2"];
var AllGroup=[GroupA1, GroupB1];
var Group = null;
for(var i = 0; i < AllGroup.length; i++){
Group = AllGroup[i];
var SubGroup = "";
for(var x = 0; x < Group.length; x++){
SubGroup = Group[x];
alert(SubGroup);
}
}
}
Before you were referencing the strings "GroupA1" "GroupB1" not the actual data contained in the subgroups that you create.