Javascript missing ) after arguments list - javascript

A JavaScript function that takes a string argument and counts its properties.
I'm not sure why it's not working I think there is some problem with the console.log line.
function superCounter (TheWord) {
var NOWords = TheWord.split('').length;
var NOLetters = TheWord.length;
var NOSpaces = 0;
for (var i = 0; i < superCounter.length; i++)
if (TheWord[i] === " ") {
NOSpaces = +1;
}
var CTCharacters = TheWord.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g, "");
var TNCharacters = CTCharacters.length;
var AWLength = NOLetters / NOWords;
console.log("words:"
NOWords, "letters:"
NOLetters, "spaces:"
NOSpaces, "chars:"
TNCharacters, "avgLength:"
AWLength)
}
superCounter("The grintch made it happen");

Your console.log statement is wrong this is the write one.
You have missed commas after every argument. console.log arguments should be separated by ,.
// console.log("words:" NOWords, "letters:" NOLetters, "spaces:" NOSpaces, "chars:" TNCharacters, "avgLength:" AWLength)
console.log("words:", NOWords, "letters:", NOSpaces, "chars:", TNCharacters, "avgLength:", AWLength);

Related

Javascript spilt function does not recognise one of the tabs in my string

I have a string with tab-separated data copied from Excel. The javascript split does not recognise the 2nd tab in the string. I have pasted the string into notepad++ to see the tabs and they are all there. Exploding the string in PHP works fine. The test code is:
function testTab(str) {
var strSplit = str.split('\t');
for (i=0; i < strSplit.length; i++){
console.log('strSplit['+i+'] = '+strSplit[i]);
}
}
The console output (where the tab between 1st and 2nd item is not recognised):
strSplit[0] = 0.02194 0.028940568
strSplit[1] = 0.05227
strSplit[2] = 0.040229885
strSplit[3] = 0.04650
strSplit[4] = 0.035630689
strSplit[5] = 0.07055
strSplit[6] = 0.015557256
strSplit[7] = 0.01960
strSplit[8] = 0.03527
strSplit[9] = 0.05276
strSplit[10] = 0.05669
strSplit[11] = 0.05680
strSplit[12] = 0.04464
strSplit[13] = 1
Unsure if the string copies correctly with all tabs, but here it is:
const str = `0.02194 0.028940568 0.05227 0.040229885 0.04650 0.035630689 0.07055 0.015557256 0.01960 0.03527 0.05276 0.05669 0.05680 0.04464 1`;
function testTab(str) {
var strSplit = str.split('\t');
for (i = 0; i < strSplit.length; i++) {
console.log('strSplit[' + i + '] = ' + strSplit[i]);
}
}
testTab(str)
Thanks for your suggestions, it inspired me to review all options.
I changed the delimiters in the regex so that the split now reads:
var strSplit = str.split(/\t/);
For some reason it now works.

Error in reading text from textarea in Javascript

In a webpage there is a textarea (id="text") and also a button (id="dlButton3").
What I have to do is to enter the text into the textarea. And when I press the button, then the following will be happened:
Text in the text area will be loaded into the function,
The text will be spitted with delimiters ""
There is a for loop to compare all the lengths of the strings, and
Print the longest one value
The problem is, with the following code, I can take the string from the text area but dun know why I cannot split the string, and it returns the error "Uncaught ReferenceError: targetString is not defined"
The code is as followed
function findlongestword(){
var testing = document.getElementById('text').value;
console.log(testing);
var strText = testing.split(" ");
var length = 0;
for (var i=0; i < strText.length; i++) {
if (length < strText[i].length) {
length = strText[i].length;
targetString = strText[i]
}
}
console.log (targetString);
}
window.onload = function(){
findlongestword();
document.getElementById("dlButton3").onclick = findlongestword;
}
What can be the error?
Many thanks for your help in advance!
Read more about block scope targetString only exists within the loop
function findlongestword() {
var testing = document.getElementById('text').value;
var strText = testing.split(" ");
var length = 0;
var targetString = '';
for (var i=0; i < strText.length; i++) {
if (length < strText[i].length) {
length = strText[i].length;
targetString = strText[i]
}
}
console.log (targetString);
}
window.onload = function() {
findlongestword();
document.getElementById("dlButton3").onclick = findlongestword;
}
"Uncaught ReferenceError: targetString is not defined"
You did not declare targetString before using it within your loop. Therefore javascript did not know where to find or 'Refer' to it after the loop ended.
By adding var targetString = ""; before the loop begins the problem will be solved.
function findlongestword(){
var testing = document.getElementById('text').value;
console.log(testing);
var strText = testing.split(" ");
//ADD HERE
var targetString = "";
var length = 0;
for (var i=0; i < strText.length; i++) {
if (length < strText[i].length) {
length = strText[i].length;
targetString = strText[i]
}
}
console.log (targetString);
}
window.onload = function(){
findlongestword();
document.getElementById("dlButton3").onclick = findlongestword;
}

Getting an infinite loop and can't see why - Javascript

I'm writing a simple little Connect 4 game and I'm running into an infinite loop on one of my functions:
var reds = 0;
var greens = 0;
function checkEmpty(div) {
var empty = false;
var clicked = $(div).attr('id');
console.log(clicked);
var idnum = parseInt(clicked.substr(6));
while (idnum < 43) {
idnum = idnum + 7;
}
console.log("idnum=" + idnum);
while (empty == false) {
for (var i = idnum; i > 0; i - 7) {
idnumStr = idnum.toString();
var checking = $('#square' + idnumStr);
var str = checking.attr('class');
empty = str.includes('empty');
console.log(empty);
var divToFill = checking;
}
}
return divToFill;
}
function addDisc(div) {
if (reds > greens) {
$(div).addClass('green');
greens++;
console.log("greens=" + greens);
} else {
$(div).addClass('red');
reds++;
console.log("reds=" + reds);
};
$(div).removeClass('empty');
}
$(function() {
var i = 1;
//add a numbered id to every game square
$('.game-square').each(function() {
$(this).attr('id', 'square' + i);
i++;
//add an on click event handler to every game square
//onclick functions
$(this).on('click', function() {
var divToFill = checkEmpty(this);
addDisc(divToFill);
})
})
})
Here is a link to the codepen http://codepen.io/Gobias___/pen/xOwNOd
If you click on one of the circles and watch the browser's console, you'll see that it returns true over 3000 times. I can't figure out what I've done that makes it do that. I want the code to stop as soon as it returns empty = true. empty starts out false because I only want the code to run on divs that do not already have class .green or .red.
Where am I going wrong here?
for (var i = idnum; i > 0; i - 7);
You do not change the i.
Do you want to decrement it by 7?
Change your for loop to the one shown below:
for (var i = idnum; i > 0; i -= 7) {
// ...
}
You also do not use loop variable in the loop body. Instead, you use idnum, I think this can be issue.
while (empty == false) {
for (var i = idnum; i > 0; i -= 7) {
idnumStr = i.toString(); // changed to i
var checking = $('#square' + idnumStr);
var str = checking.attr('class');
empty = str.includes('empty');
console.log(empty);
var divToFill = checking;
// and don't forget to stop, when found empty
if (empty) break;
}
}
I add break if empty found, because if we go to next iteration we will override empty variable with smallest i related value.
You can also wrap empty assignment with if (!empty) {empty = ...;} to prevent this override, but I assume you can just break, because:
I want the code to stop as soon as it returns empty = true
Offtop hint:
while (idnum < 43) {
idnum = idnum + 7;
}
can be easy replaced with: idnum = 42 + (idnum%7 || 7)
Change to this:
for (var i = idnum; i > 0; i = i - 7) {
You are not decrementing the i in your for loop
Building on what the others have posted You would want to change the value of empty inside the for loop. because obviously the string still checks the last string in the loop which would always return false.
while(empty==false){
for (var i = idnum; i > 0; i -= 7) {
// your other codes
if (!empty) {
empty = str.includes('empty');
}
}

pushing into arrays in javascript

My script (is meant to) grab text from the a page (which works fine) and then splits it by by newline (\n) and puts each splitted string into an array called "dnaSequence"; from there it loops through each element in the array and if the string contains the character ">" it assigns that string to the "var header_name", else it pushes all other lines into a new array called "dnaSubseq". The original text looks something like this:
>header_1
gctagctagc
cgcgagcgagc
>header_2
gcgcatgcgac
When I execute the code it fails to alert on anything. Here is the code:
function loaderMy() {
var dnaSubseq = [];
var dnaSequence = [];
var header_name = "";
var splittedLines = document.getElementById("page-wrapper").innerText;
dnaSequence = splittedLines.split('\n');
for (var i = 0; i < dnaSequence.length; i++) {
if (dnaSequence[i].match(/>/)) {
header_name = dnaSequence[i];
alert(header_name);
}
else {
dnaSubseq.pushValues(dnaSequence[i]);
}
alert(dnaSubseq);
}
}
Change
dnaSubseq.pushValues(dnaSequence[i]);
To
dnaSubseq.push(dnaSequence[i]);
If it doesn't alert anything, that means you forgot to invoke the function :)
loaderMy();
http://jsfiddle.net/zszyg5qx/
Try this function
function loaderMy() {
var dnaSubseq = [];
var dnaSequence = [];
var header_name = "";
var splittedLines = document.getElementById("page-wrapper").innerText;
dnaSequence = splittedLines.split('\n');
for (var i = 0; i < dnaSequence.length; i++) {
if (dnaSequence[i].match(/>/)) {
header_name = dnaSequence[i];
alert(header_name);
}
else {
dnaSubseq.push(dnaSequence[i]);
}
alert(dnaSubseq);
}
}

Multiplying Variables Not Alerting

I have a script which calls variable values from input fields and multiplies them,
At the minute my function isnt executing, Im getting no alert neither, I think this is because of my if statement, can anybody see whats going wrong?
function Calculate() {
var ContentMinutes = document.getElementById ("ContentMinutes").value;
var ContentMinutesSelect = document.getElementById('ContentMinutesDD')
.options[document.getElementById('ContentMinutesDD').selectedIndex].value
if (ContentMinutesSelect == 0.0166)
{
var RenderingHours = 10;
var VideoHours = 5;
var VideoSeconds = 1;
document.getElementById("RenderHours").innerHTML=RenderingHours;
document.getElementById("VideoHours").innerHTML=VideoHours;
document.getElementById("VideoSeconds").innerHTML=VideoSeconds;
}
else if (ContentMinutesSelect == 0.0003)
{
var RenderingHours = 1540;
var VideoHours = 54;
var VideoSeconds = 1;
document.getElementById("RenderHours").innerHTML=RenderingHours;
document.getElementById("VideoHours").innerHTML=VideoHours;
document.getElementById("VideoSeconds").innerHTML=VideoSeconds;
}
else
{
var RenderingHours = 6410;
var VideoHours = 345;
var VideoSeconds = 124;
document.getElementById("RenderHours").innerHTML=RenderingHours;
document.getElementById("VideoHours").innerHTML=VideoHours;
document.getElementById("VideoSeconds").innerHTML=VideoSeconds;
}
var NoOfFrames = document.getElementById ("NoOfFrames").value;
//var EstimatedCoreHours = document.getElementById ("EstimatedCoreHours").value;
var ServiceLevel = document.getElementById('SerivceLevelDD')
.options[document.getElementById('SerivceLevelDD').selectedIndex].value;
var RenderHours = 1;
var CoresInTest = document.getElementById ("CoresInTest").value;
var EstimatedCoreHours = GetNumeric(NoOfFrames)
* GetNumeric(RenderingHours)
* GetNumeric(CoresInTest);
var EstimatedTotal = GetNumeric(ServiceLevel)
* GetNumeric(EstimatedCoreHours);
alert('Estimated Cost = '
+EstimatedTotal.toFixed(2)
+ 'Estimated Core Hours = '
+EstimatedCoreHours);
document.getElementById("EstimatedCoreHours").innerHTML =
EstimatedCoreHours.toFixed(2);
document.getElementById("EstimatedTotal").innerHTML =
EstimatedTotal.toFixed(2);
document.getElementById("EstimatedCoreHours").style.backgroundColor="yellow";
document.getElementById("EstimatedTotal").style.backgroundColor="yellow";
}
function GetNumeric(val) {
if (isNaN(parseFloat(val))) {
return 0;
}
return parseFloat(val);
}
if (ContentMinutesSelect == 0.0166) i think when you do .value you will get string result.
So your comparision should be
if (ContentMinutesSelect == "0.0166")
Your code will display no alert if any line before it results in an error , like if there isn't an element with the id 'ContentMinutes' in your document . The best way to debug would be to use something like firebug , or you could always put in a bunch of alerts and figure out what goes wrong.

Categories

Resources