Passing loop counter as argument in Node.js - javascript

I was trying this as a tutorial from nodeschool, and I'm new to Node.js. The code is below, and I know the problem in it, but I am not able to resolve it. The problem is that j has a value of 3 for every iteration of the loop inside the bl function, but Why is that happening?
var bl = require('bl');
var http = require('http');
var urls = process.argv.slice(2);
var result = [];
for (var i = 0; i < urls.length; i++) {
result.push(null);
}
for(j = 0 ; j < urls.length; ++j){
http.get(urls[j],function(response){
response.pipe(bl(function(err,data){
//console.log(result[i]);
//console.log(data.toString());
result[j] = data.toString();
console.log('J : ' + j);
console.log(data.toString());
var flag = 0;
for (var i = 0; i < result.length; i++) {
console.log('here1');
console.log(result[i]);
if(result[i] == null){
flag = 1;
console.log('here');
break;
}
}
if(flag == 0){
for (var i = 0; i < result.length; i++) {
console.log(result[i]);
}
}
}));
});
}

http.get is an async request but the for is sync so for is "most fast" and when http.get finish to download the url data then variable "j" takes last value.
You have another mistake I think, on your for loop you increase variable "j" as "++j" and it will be "j++".
To fix the first issue (variable "j" value) you can use an anonymous function and pass the value "j" like:
for(j = 0 ; j < urls.length; j++) {
(function(j) {
http.get(urls[j],function(response){
response.pipe(bl(function(err,data){
//console.log(result[i]);
//console.log(data.toString());
result[j] = data.toString();
console.log('J : ' + j);
console.log(data.toString());
var flag = 0;
for (var i = 0; i < result.length; i++) {
console.log('here1');
console.log(result[i]);
if(result[i] == null){
flag = 1;
console.log('here');
break;
}
}
if(flag == 0){
for (var i = 0; i < result.length; i++) {
console.log(result[i]);
}
}
}));
});
}(j));
}
There are a lot of code but in resume i did this:
for(j = 0 ; j < urls.length; j++) {
(function(j) {
/* your code inside this function will have the correct
value to variable "j" if you use async methods */
} (j));
}

Related

How do I fix the undefined result I keep getting from this?

So I'm doing the HackerRank superDigit challenge and even though I have the correct value for all the informal test cases, the Output box says that the result is undefined.
I'm not really getting what undefined is all about or how a variable with a value returns as undefined.
function superDigit(n, k) {
// Write your code here
var nArr = [];
for(let i = 0; i < n.length; i++)
{
nArr.push(n[i]);
}
console.log('nArr: ' + nArr);
var nComb = 0;
for(let i = 0; i < nArr.length; i++)
{
nComb += parseInt(nArr[i]);
}
console.log('nComb: ' + nComb);
var nMult = nComb *= k;
console.log('nMult: ' + nMult);
console.log('');
if(nMult < 10)
{
return nMult;
}
else
{
superDigit(nMult.toString(),1);
}
}
You probably want to return the superDigit result as well. So when calling superDigit recursively, add the return statement. I also cleaned up the console.log calls a bit so its more readable to me.
function superDigit(n, k) {
var nArr = [];
for(let i = 0; i < n.length; i++)
{
nArr.push(n[i]);
}
var nComb = 0;
for(let i = 0; i < nArr.length; i++)
{
nComb += parseInt(nArr[i]);
}
var nMult = nComb *= k;
console.log('nMult:', nMult, 'nArr:', nArr, 'nComb:', nComb);
if(nMult < 10)
{
return nMult;
}
else
{
return superDigit(nMult.toString(),1);
}
}
document.getElementById('result').innerText = superDigit("200", 20);
<html>
<body>
<p id="result"></p>
</body>
</html>

window.location.reload(); stuck in infinite loop

I want this function to loop through all items, if it finds the right item to load its page, and if it doesn't find the right item it should reload the page and for loop again. When I delete the window.location.reload(); it loads normally to the item page. This is the code:
var item_name = "Washed";
var item_color = "Red";
function pickItem() {
let items = document.getElementsByClassName("name-link");
for(i = 0; i < items.length; i++) {
if((items[i].innerHTML).includes(item_name)) {
for(j = 0; j < items.length; j++) {
if((items[j].innerHTML).includes(item_color)) {
if(items[i].href == items[j].href) {
window.location.assign(items[i, j].href);
}
}
}
}
}
window.location.reload();
}
In the following form it works as I want, but why does it need the chrome.storage function to work?(I used it with the chrome.storage before, but it was too slow for my purposes so I had to change it.)
var item_name = "Washed";
var item_color = "Red";
function pickItem() {
let items = document.getElementsByClassName("name-link");
chrome.storage.sync.get(["itemName", "color"], function(data) {
for(i = 0; i < items.length; i++) {
if((items[i].innerHTML).includes(item_name)) {
for(j = 0; j < items.length; j++) {
if((items[j].innerHTML).includes(item_color)) {
if(items[i].href == items[j].href) {
window.location.assign(items[i, j].href);
chrome.storage.sync.set({"item_url": items[i, j].href});
}
}
}
}
}
})
window.location.reload()
}
I'd recommend adding a boolean variable which indicates if a location to navigate to has been found yet and wrap the call to window.location.reload() inside an if-block which checks the state of the variable.
e.g.
function pickItem() {
let items = document.getElementsByClassName("name-link");
let found = false;
for (i = 0; i < items.length; i++) {
if ((items[i].innerHTML).includes(item_name)) {
for (j = 0; j < items.length; j++) {
if ((items[j].innerHTML).includes(item_color)) {
if (items[i].href == items[j].href) {
found = true;
window.location.assign(items[i, j].href);
}
}
}
}
}
if (!found) {
window.location.reload();
}
}

Randomly getting Uncaught TypeError: Cannot read property 'substring' of undefined

success: function(data) {
var timeslots = new Array('09:00am', '09:15am', '09:30am', '09:45am', '10:00am', '10:15am', '10:30am', '10:45am', '11:00am', '11:15am', '11:30am', '11:45am', '02:00pm', '02:15pm', '02:30pm', '02:45pm', '03:00pm', '03:15pm', '03:30pm', '03:45pm', '04:00pm', '04:15pm', '04:30pm');
var booked = '';
var bookedSlots = [];
var t_slots;
if (data.bookedslots.length == timeslots.length) {
if (manageDay) {
$('.manageSlots .timeSlot').remove();
}
alert('No Available Slots');
$(where).find('select.time').empty();
return false;
}
for (var t = 0; t < data.bookedslots.length; t++) {
booked = data.bookedslots[t]['time'].substr(0, data.bookedslots[t]['time'].length - 3);
bookedSlots.push(booked);
}
for (var i = 0; i < timeslots.length; i++) {
for (var j = 0; j < bookedSlots.length; j++) {
///// getting the error on this line ////////if(timeslots[i].substring(0,5) === bookedSlots[j]){
timeslots.splice(i, 1);
}
}
}
for (var z = 0; z < timeslots.length; z++) {
t_slots += '<option value="' + timeslots[z] + '">' + timeslots[z] + '</option>';
}
}
The problem is that you have spliced out timeslots[i], but in the next iteration of j you try to use it. If it was the last item in the array you will get an error. If you splice, you should break on the next line to abort the rest of the j loop.
for (var i = 0; i < timeslots.length; i++) {
for (var j = 0; j < bookedSlots.length; j++) {
if(timeslots[i].substring(0,5) === bookedSlots[j]){
timeslots.splice(i, 1);
break;
}
}
}

Javascript: function and its argument

I've a problem with my function and its arguments... this is the code:
function elab(){
var up = arguments[0];
var id = arguments[1];
len = arguments.length - 3;
for(var a = 1; a <= 10; a++){
arg = (arguments[2] + a); // id tag html : [nome][num]
document.getElementById(arg).style.display = "block";
}
for (var i = 3; i < len; i++) {
alert('test1');
document.getElementById(arguments[i]).style.display = "none";
alert('test2');
}
change_price(up, id);
}
The script hangs at the second cycle: it prints 'test1' but not 'test2'.
Where is the error?
thx all ;)
Note that this advice should be used for all things unsure:
for (var i = 3; i < len; i++) {
var node = document.getElementById(arguments[i]);
if (node) {
node.style.display = "none"; // block
}
}
In other words, always test if an element can be found if you're not 100% sure. To be even more pedantic:
for (var i = 3; i < len; i++) {
var node = document.getElementById(arguments[i]);
if (!node) {
throw "Element " + arguments[i] + " not found.";
}
node.style.display = "none"; // block
}

remove null value in javascript

am having script with working condition but many for loop is there so any way to do this...to simplify this ...am new to script kindly help on this....
function change()
{
//document.getElementById("Geography").options[7]=new Option("", "newval", true, false);
var geo = document.getElementById("Geography").options;
var zon = document.getElementById("zone").options;
var coun = document.getElementById("country").options;
for (var i = 0; i < geo.length; i++)
{
if (geo[i].innerHTML == "Null Value" || geo[i].innerHTML == "")
{
document.getElementById("Geography").options[i] = null;
}
}
for (var i = 0; i < coun.length; i++)
{
alert("Loop1" + i);
if (coun[i].innerHTML == "Null Value")
{
document.getElementById("country").options[i] = null;
}
}
for (var i = 0; i < zon.length; i++)
{
//alert("Loop1" + i);
if (zon[i].innerHTML == "Null Value")
{
document.getElementById("zone").options[i] = null;
}
}
}
To remove an option, call removeChild() on the parent element.
var geoSel = document.getElementById("Geography");
var geo = geoSel.options;
for (var i = geoSel.options.length-1; i >= 0; i--) {
if (geo[i].innerHTML == "Null Value" || geo[i].innerHTML == "") {
geo.removeChild(geo[i]);
}
}
I count down instead of up because removing a child will cause the indexes of all the following children to be shifted down. In a count-up loop, that will cause elements to be skipped.
use this UPDATED DEMO
function change(){
var optionsArr = [];
optionsArr.push(document.getElementById("Geography").options);
optionsArr.push(document.getElementById("zone").options);
optionsArr.push(document.getElementById("country").options);
var optArrlenght = optionsArr.length;
for ( var j = 0; j < optArrlenght; j++){
var options = optionsArr[j];
var optionslength = options.length;
for (var i = 0; i < optionslength; i++)
{
if (options[i].innerHTML == "Null Value" || options[i].innerHTML == "")
{
options[i].remove();
i--;
optionslength--;
}
}
}
}
change();

Categories

Resources