I have the following code that transmits the essence of the problem:
var body = "";
for(var i=0; i<=5000; i++) {
body += "if(str==='value" + i + "') 1==1;\n";
}
body += "return str;";
var f1 = new Function("str", body);
var f2 = new Function("str", body);
console.log(f1('test1'));
console.log(f2('test2'));
// main loop
for(var i=0; i<100000; i++) {
f1("string");
f2("string");
console.log(i);
}
console.log("fin!");
Why the main loop cycle does not work out until the end, and the program exits (thus no error information is not displayed)?
PS line "fin!" will not be displayed.
My nodejs version is 5.0.0
My actual output:
test1
test2
1
2
3
.
.
~1971
Try this:
var i = 0;
for(i=0; i < 5001; i++) {
body += "if(str==='value" + i + "') 1==1;\n";
}
But i think the functions are bugged...
Related
This is Javascript code for some quiz i am making.
In my case table.length = 2, and function is repeating 2 times with parameter for first table and second.
But why command shows 4 times in console?
console.log("Hello");
.
function start(){
var brojac =0;
var table = document.getElementsByTagName("table");
for (i =0; i<table.length ; i++){
jednoPitanje(i);
brojac += parseInt(jednoPitanje(i))
}
console.log("Sakupili ste ukupno " + brojac + " bodova");
}
function jednoPitanje(x) {
var odgovori ="";
var table = document.getElementsByTagName("table");
var tableN = table[x];
var input = tableN.getElementsByTagName("input")
var brojInputa = tableN.getElementsByTagName("input").length;
//Uzima bodove,kategoriju i index tocnih odgovora
var bodovi =tableN.classList[2];
var kategorija =tableN.classList[1];
var tocni = tableN.classList[0];
console.log("Hello");
//Iteracija kroz sve checkboxsove u tablici
for (j =0; j<brojInputa ; j++){
if(input[j].checked==true){
odgovori += tableN.getElementsByTagName("input")[j].value;
}
}
if(odgovori == tocni){
}
else{bodovi = 0;}
return bodovi;
}
You are calling console.log("Hello"); in the function jednoPitanje(). You call this function twice inside your loop:
jednoPitanje(i); // <-- this cause console.log() to run
brojac += parseInt(jednoPitanje(i)) // <-- this also causes the console.log()
and since your loop runs twice it prints four times.
It's not immediately clear if you need that function to run twice, but if you don't, you can just remove the first call:
for (i =0; i<table.length ; i++){
brojac += parseInt(jednoPitanje(i))
}
or if you prefer the extra clarity:
for (i =0; i<table.length ; i++){
var bodovi = jednoPitanje(i);
brojac += parseInt(bodovi)
}
I am trying to decode my string using JavaScript. Here is my code on JSBin.
decordMessage('oppeeennnn','1234');
function decordMessage(m,k) {
var msg = m.split('');
var keysplit = k.split('');
var str ='';
var j =0
for (var i=0;i<msg.length;){
str += msg[i];
if(j < keysplit.length -2 &&i < keysplit.length && keysplit[j]){
i = i + parseInt(keysplit[j]);
j++;
}
console.log(i +"i")
console.log(str);
}
console.log("after");
console.log(str);
}
I make a function in which message and key is passed.
Expected output :: open
Actually string charters are repeated in input message (encrypted message) using key. So I need to decode the message.
You forgot to put a break in the else condition, that's why it was looping infinitely till it ran out of memory. Run it in a browser and the tab will crash:
decordMessage('oppeeennnn','1234');
function decordMessage(m,k) {
var msg = m.split('');
var keysplit = k.split('');
var str ='';
var j =0
for (var i=0;i<msg.length;){
str += msg[i];
if(j < keysplit.length &&i < keysplit.length && keysplit[j]){
i = i + parseInt(keysplit[j]);
j++;
}
else
break;
}
console.log("after");
console.log(str); // prints open
}
By the way, a better way to write the loop would be:
function decordMessage(m,k) {
var msg = m.split('');
var keysplit = k.split('');
var str = '';
var j = 0, i = 0;
while (j < keysplit.length
&& i < msg.length) {
str += msg[i];
i += parseInt(keysplit[j]);
j++;
}
console.log(str)
}
This may helps you.
decordMessage('oppeeennnn', '1234');
function decordMessage(m, k) {
var arr = m.split("");
uniqueArray = arr.filter(function(item, pos) {
return arr.indexOf(item) == pos;
});
console.log(uniqueArray.join(""));
}
Assuming encryption logic goes as 123456....
Sample here
I have a for loop which looks like this:
for (var i = 0; i < list.length; i++) {
It is looping through Firebase data in the database and returning all the data in the database.
However, I want it to only go up to the first 10 database items. So I changed the loop to:
for (var i = 0; i < 9; i++) {
But this fails to display any results when the there are less than 10 pieces of data in the database. However, if I set the number to however many objects I have in the database, for example 10 because I have 10 objects, it displays them all. But any less than this number and I just get a blank webpage.
Here is the webpage when I have 10 objects in my Firebase database:
And here it is when I remove one of those objects:
I have no idea why this is happening - The logic is correct - if i is less than 9 then display the data - But instead it only displays it when it equals 9.
Here is the full JS:
function refreshUI(list) {
var lis = '';
var lis2 = '';
var lis3 = '';
var lis4 = '';
for (var i = 0; i <= 9; i++) {
lis += '<li data-key="' + list[i].key + '" onclick="addText(event)">' + list[i].book + '</li>';
lis2 += genLinks(list[i].key, list[i].book)
};
for (var i = 10; i < list.length; i++) {
lis3 += '<li data-key="' + list[i].key + '" onclick="addText(event)">' + list[i].book + '</li>';
lis4 += genLinks(list[i].key, list[i].book)
};
document.getElementById('bookList').innerHTML = lis;
document.getElementById('bookList2').innerHTML = lis2;
document.getElementById('bookList3').innerHTML = lis3;
document.getElementById('bookList4').innerHTML = lis4;
};
function genLinks(key, bkName) {
var links = '';
links += '<img src="images/bin.png" style="width: 24px; height: 24px; transform: translateY(-7px); opacity: .4;"></img> ';
return links;
};
function del(key, bkName) {
var response = confirm("Are certain about removing \"" + bkName + "\" from the list?");
if (response == true) {
// build the FB endpoint to the item in movies collection
var deleteBookRef = buildEndPoint(key);
deleteBookRef.remove();
}
}
function buildEndPoint (key) {
return new Firebase('https://project04-167712.firebaseio.com/books/' + key);
}
// this will get fired on inital load as well as when ever there is a change in the data
bookList.on("value", function(snapshot) {
var data = snapshot.val();
var list = [];
for (var key in data) {
if (data.hasOwnProperty(key)) {
book = data[key].book ? data[key].book : '';
if (book.trim().length > 0) {
list.push({
book: book,
key: key
})
}
}
}
// refresh the UI
refreshUI(list);
});
If anybody has any help I'd greatly appreciate it!
When the list size is shorter than 10, you will get an error in the loop because you will eventually address a property (like key) that does not exist on list[i] (since it is undefined). If you would check the console, you would notice that this error is reported.
To fix this, change the condition of the first for loop like this:
for (var i = 0; i < Math.min(10, list.length); i++) {
This way, the loop will never iterate to an entry that does not exist. It will stop after 9 or after list.length-1 whichever comes first.
Alternatively, you can just put the two conditions with an && operator:
for (var i = 0; i < 10 && i < list.length; i++) {
I'm new here and to JavaScript. I have an assignment that asks "create a new property in the foodInfo object plus the value of the toppings variable, and set the ne property's value to to value of the current element in the toppingBoxes array."
Here is the code I have that is not working, I have tried multiple things but cant get it to print out the toppings on the page:
for (var i = 0; i < toppingBoxes.length; i++) {
if (toppingBoxes[i].checked) {
toppings = toppings + 1;
foodInfo.topping[toppings] = toppingBoxes[i].value;
}
}
Here is the code the assignment gave me to print it, so this code is correct, but the code above is what I need help with:
foodSummary.innerHTML += "<ul>";
for (var i = 1; i < 6; i++) {
if (foodInfo["topping" + i]) {
foodSummary.innerHTML += "<li>" + foodInfo["topping" + i] + "</li>";
}
}
foodSummary.innerHTML += "</ul>";
I know the code stops running when it hits the line "foodInfo.topping[toppings] = toppingBoxes[i].value;" so I know that is wrong. I am having trouble with the instructions I mentioned above...any help to get this working? Thank you in advance!!
Try this:
var toppings = 0;
for (var i = 0; i < toppingBoxes.length; i++) {
if (toppingBoxes[i].checked) {
toppings = toppings + 1;
foodInfo['toppings' + toppings] = toppingBoxes[i].value;
}
}
I have a bit of an issue at the moment that I am hoping one of you can help me with. I have tried several things, and I just can't get it. I am trying to print a triangle of asterisks using JavaScript. The program is to ask the user for the amount of rows, and then the direction. I haven't even started with the direction yet because I can't get the rows to work. Odd thing is that I can get it to print out the triangle hard-coding the function call.
This is the JS file:
function myTriangle(){
var result = "";
var totalRows = document.getElementById('rows').value;
var direction = document.getElementById('UpOrDown').value;
for (var i = 1; i <= totalRows; i++){
document.writeln("count");
for (var j = 1; j <= 1; j++)
{
result += "*";
}
result += "<br/>";
}
return result;
}
var answer = myTriangle();
document.getElementById('myDiv').innerHTML = answer;
This is the HTML file:
<!DOCTYPE html>
<head>
<title>Lab 2</title>
<script src="scripts.js", "div.js"></script>
</head>
<body>
<form name="myForm">
<fieldset>
<legend>Input Fields</legend>
rows: <input type="text" id="rows" /><br>
direction: <input type="text" id="UpOrDown" /><br>
press: <input type="button" value="GO!" id="myButton"
onclick="myTriangle();"/>
</fieldset>
</form>
<div id="myDiv">
</div>
</body>
The output will be something like this:
*
**
***
****
*****
Generally there are four types of triangle -
1.)* 2.) *** 3.) * 4.) ***
** ** ** **
*** * *** *
Code for 1 -
var ast = [],
i, j = 4;
for (i = 0; i < j; i++) {
ast[i] = new Array(i + 2).join("*");
console.log(ast[i]);
}
Code for 2 -
var ast = [],
i, j = 4;
for (i = j-1; i >=0; i--) {
ast[i] = new Array(i + 2).join("*");
console.log(ast[i]);
}
Code for 3 -
var ast = [],
i, j = 4;
for (i = 0; i < j; i++) {
ast[i] = new Array(j - i).join(' ') + new Array(i + 2).join("*");
console.log(ast[i]);
}
Code for 4 -
var ast = [],
i, j = 4;
for (i = j-1; i >=0; i--) {
ast[i] = new Array(j - i).join(' ') + new Array(i + 2).join("*");
console.log(ast[i]);
}
To print asterisk in document rather than console -
document.getElementById('anyElement').innerHTML+=ast[i] + '<br />';
document.writeln will completely wipe the page unless it's called while the page is loading.
Therefore it will destroy myDiv, causing the getElementById to fail.
Furthermore, I'm not sure what you're trying to achieve with that <script> tag, but it looks like you need two of them.
EDIT: Oh, and this: for (var j = 1; j <= 1; j++) will only ever iterate once.
EDIT 2: Here's my implementation of a solution.
This isn't a valid script tag.
<script src="scripts.js", "div.js"></script>
You need to break it up into two tags:
<script src="scripts.js"></script>
<script src="div.js"></script>
This is my solution, it uses es2015 .replace() but there is a nice
polyfill for es5 as well here:
var output = document.getElementById('output');
function triangle (size) {
for (var i = 1; i <= size; i++) {
output.innerHTML += '*'.repeat(i) + '<br>';
}
}
triangle(2);
This is a solution in ES3/5
var output = document.getElementById('output');
function triangle(size) {
var allLines = '';
for (var i = 1; i <= size; i++) {
var oneLine = createLine(i);
allLines += oneLine;
}
return allLines;
}
function createLine(length) {
var aLine = '';
for (var j = 1; j <= length; j++) {
aLine += '*';
}
return aLine + "<br/>";
}
output.innerHTML += triangle(3);
<div id='output'></div>