Set an item to empty in array Javascript - javascript

After initialing an array, it contains empty elements. I want to set an element back to empty after setting an value. But it doesn't work however I set it to undefined/null.
var a = Array(20181231);
// it will not run.
a.forEach(e => {console.log(++i + ' - ' + e);});
var i = 0;
a[12] = 12;
a[2018] = 2018;
// it loop twice
a.forEach(e => {console.log(++i + ' - ' + e);});
a[12] = undefined;
// expecting one time, but it still loop twice.
a.forEach(e => {console.log(++i + ' - ' + e);});

You could take the delete operator and remove the element of the array.
var a = Array(20181231);
a.forEach(e => console.log(++i + ' - ' + e)); // no loop
var i = 0;
a[12] = 12;
a[2018] = 2018;
a.forEach(e => console.log(++i + ' - ' + e)); // two elements
delete a[12];
a.forEach(e => console.log(++i + ' - ' + e)); // one element

Related

Replacing null with 0 when summing values

I have a function that sums my values and everything works fine, but only when all inputs have a value entered. However, I would like default to have 0 assigned to it.so that the function works when at least one value is given . How to do it ?.
var DeductiblepercentageM = thisPointer.entity.getValue('number.DeductiblepercentageM[' + i + ']');
var InsuranceLimitM = thisPointer.entity.getValue('number.InsuranceLimitM[' + i + ']');
var insuranceRaitingM = thisPointer.entity.getValue('number.insuranceRaitingM[' + i + ']');
var InsurerNumberM = thisPointer.entity.getValue('number.InsurerNumberM[' + i + ']');
DeductiblepercentageM = DeductiblepercentageM.replace(",", ".");
DeductiblepercentageM = parseFloat(DeductiblepercentageM)
InsuranceLimitM = InsuranceLimitM.replace(",", ".");
InsuranceLimitM = parseFloat(InsuranceLimitM)
insuranceRaitingM = insuranceRaitingM.replace(",", ".");
insuranceRaitingM = parseFloat(insuranceRaitingM)
InsurerNumberM = InsurerNumberM.replace(",", ".");
InsurerNumberM = parseFloat(InsurerNumberM)
//log the outcome of decimal separator change
var positionSum = +(DeductiblepercentageM + InsuranceLimitM +insuranceRaitingM + InsurerNumberM);
jQ('[id="DeductibleM[' + i + ']"]').val(positionSum);
thisPointer.entity.setValue('DeductibleM[' + i + ']', positionSum);
thisPointer.entity.mergeLocal(true);
if (totalSum != "NaN") {
totalSum = +(totalSum + positionSum).toFixed();
}
}
else {
totalSum = "-";
}
According to #Terry
var InsuranceLimitM = thisPointer.entity.getValue('number.InsuranceLimitM[' + i + ']') || 0;
adding || 0 to the end of the code helps and makes the code count right away

Google Api Calendar If else ,done with javascript

So I'm doing Google Calendar Api, that shows all the booked things for that day. I'm trying to get this code to print 'Vapaa' (means free in finnish and is shown if there's nothing booked in that time) only once but still print the rest of the appointments that come later that day. Here's the code that does the if else
if (events.length > 0) {
for (i = 0; i < events.length; i++) {
var event = events[i];
var when = new Date(event.start.dateTime);
var hs = addZero(when.getHours());
var ms = addZero (when.getMinutes());
var end = new Date(event.end.dateTime);
var he = addZero(end.getHours());
var me = addZero (end.getMinutes());
var now = new Date();
var hn = addZero(now.getHours());
var mn = addZero (end.getMinutes());
if (!when) {
when = event.start.date;
}
if (when.getTime() <= now.getTime() && now.getTime() <= end.getTime()){
appendPre(event.summary + ' ' + hs + (':') + ms + '' + (' - ') + '' + he + (':') + me + '');
} else {
appendPre('Vapaa');
appendPre(event.summary + ' ' + hs + (':') + ms + '' + (' - ') + '' + he + (':') + me + '');
}
return;
}
} else {
appendPre('Ei varauksia');
}
Also the appendPre is printed to html with this code
function appendPre(message) {
if (message != 'Vapaa'){
var pre = document.getElementById('booked');
var textContent = document.createTextNode(message + '\n' + '\n');
} else {
var pre = document.getElementById('free');
var textContent = document.createTextNode(message + '\n' + '\n');
}
pre.appendChild(textContent);
}
I'm so lost so any help would be awesome.
return; stops right where it is and exits the function, so your for loop will only run once with the return in there. See W3C for more info.
Typically, if you want to exit only the loop, but continue in the function (if you have code after it, it doesn't look like you've shown that here), you can use break;. If you want to skip the rest of the stuff in the for loop (nothing is shown in your example), but continue iterating onto the next entry, you can use continue;. See W3C for more details.

Render a RealTime Clock after append in Jquery

I have tried many ways to make a live clock (with seconds) appear in a rendered table but it's not working propperly. The clock stays static, not showing second by second. I'm doing the following :
function myTable(){
var table = $('<table></table>');
table.append($('<tr>')
.append($('<td>')
.addClass('col2 data')
.attr('rowspan', '2')
.append($('<span>')
.attr('id', 'date_time')
)
)
)
$("#myDiv").html(table)
}
liveClock();
var liveClock = function () {
date = new Date;
//some logic here to generate the data I need the result above ( no problems here )
result = '' + d + '/' + month + '/' + year + ' ' + h + ':' + m + ':' + s;
var setDateTime = function() {
$("#date_time").html(result);
return false;
};
var everySec = setInterval(setDateTime, 1000);
}
Your problem is that you're never updating result, so each time your code fires SetDateTime, it renders the same date in the table. Move these lines:
date = new Date;
//some logic here to generate the data I need the result above ( no problems here )
result = '' + d + '/' + month + '/' + year + ' ' + h + ':' + m + ':' + s;
Into your setDateTime function.

Change countdown when refresh the page?

I have my own webshop and on the home page i have a lot of products with countdown.
So whats the problem?
The problem is, when i have many javascripts on home page then the broser will freezing, getting slow.
How i know this is an javascript problem ? I tried to disable javascript on the browser and my website works normal.
/*!
*
* Brian2000: BK_Countdown v1.1
* AKA: Brian's jQuery Robust Date/Time Countdown
* http://brian2000.com
*
* Copyright 2012-2013, Brian Kennedy
* Licensed under the GPL Version 3 license
* http://www.gnu.org/licenses/gpl-3.0.en.html
*
* Date: Wed Jan 9 2013 2:54PM EST
*
* You can't remove this part, and if you make changes or improve things, please keep me informed.
* Thank you, enjoy, and support Open Source!
*/
/*
This portion explains how to use the counter, I recomend not deleting it either ;-)
VARS [required]
------------------------------------------------
container: ID of Element for counter
targetDate: MM/DD/YYYY
targetTime: HH:MM:SS (0-23 Hour) [seconds are optional]
OPTIONS:
------------------------------------------------
order: format/output order
order: 1 = Label + Spacer + Value
order: 2 = Value + Spacer + Label (reverse from order 1)
spacer: text/string seperator between label and value
element: html element for label and value containers (default is span)
end: Message to display when date has passed
dayOf: Message to display on day of counter expiration
*/
function BK_CountDown(container, targetDate, targetTime, opts) {
/////////////////////////////////////////////////////
//vars
this.opts = opts;
this.complete = false; //for exiting interval
this.container = container; //target
DArray = targetDate.split('/');
this.targetDate = DArray[0] + '/' + DArray[1] + '/' + DArray[2];
TArray = targetTime.split(':');
this.targetHour = TArray[0]; //hr
this.targetMin = TArray[1]; //min
if (typeof TArray[2] == 'undefined') { //sec
this.targetSec = 0;
}else{
this.targetSec = TArray[2];
}
/////////////////////////////////////////////////////
// options
var defaults = {
'order' : "1",
'spacer' : ':',
'element' : 'span',
'end' : "Deal is ended!",
'dayOf' : "Deal is ended!"
}
if(typeof this.opts != "undefined") { //if options were assigned...
for(var i in defaults) { //assign defaults for unchanged opts
if(typeof this.opts[i] == "undefined") {
this.opts[i] = defaults[i];
}
}
}else{ //no options were assigned
this.opts = defaults;
}
/////////////////////////////////////////////////////
/////////////////////////////////////////////////////
//////// assembly
/////////////////////////////////////////////////////
s = this.opts['spacer'];
this.c = container.substring(1);
e = this.opts['element'];
if(this.opts['order'] == 2){
//reverse assembly
$(container).append('<' + e + ' id="' + this.c + '_count_days" class="count_days"></' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_txt_days" class="txt_days">' + s + ' Days</' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_count_hours" class="count_hours"></' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_txt_hours" class="txt_hours">' + s + ' :</' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_count_min" class="count_min"></' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_txt_min" class="txt_min">' + s + ' :</' + e + '>');
}
else{
//default assembly
$(container).append('<' + e + ' id="' + this.c + '_txt_days" class="txt_days">Days ' + s + '</' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_count_days" class="count_days"></' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_txt_hours" class="txt_hours">Hours ' + s + '</' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_count_hours" class="count_hours"></' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_txt_min" class="txt_min">Minutes ' + s + '</' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_count_min" class="count_min"></' + e + '>');
}
/////////////////////////////////////////////////////
/////////////////////////////////////////////////////
//////// Count Update function
this.count_update = function count_update(){
date = new Date(); //NOW
targetDate = new Date(this.targetDate);
targetDate.setHours(this.targetHour);
targetDate.setMinutes(this.targetMin);
targetDate.setSeconds(this.targetSec);
var UDate = Math.round(date.getTime()/1000);
var UTargetDate = Math.round(targetDate.getTime()/1000);
differance = UTargetDate - UDate;
days=Math.floor(differance/(60*60*24)*1);
hours=Math.floor((differance%(60*60*24))/(60*60)*1);
minutes=Math.floor(((differance%(60*60*24))%(60*60))/(60)*1);
seconds=Math.floor((((differance%(60*60*24))%(60*60))%(60))*1);
//if range is 0 don't display range
//days
if(days <= 0){$(this.container + '_count_days').remove();$(this.container + '_txt_days').remove();}
else{$(this.container + '_count_days').text(days);}
//hours
if(days <= 0 && hours <= 0){$(this.container + '_count_hours').remove();$(this.container + '_txt_hours').remove();}
else{$(this.container + '_count_hours').text(hours);}
//min
if(days <= 0 && hours <= 0 && minutes <= 0){$(this.container + '_count_min').remove();$(this.container + '_txt_min').remove();}
else{$(this.container + '_count_min').text(+minutes);}
//seconds
$(this.container + '_count_sec').text(seconds);
//Singular text for 'reverse' assembly
if(this.opts['order'] == 2){
if(days <= 1){$(this.container + '_txt_days').text(this.opts['spacer'] + ' dag en ');}
else{$(this.container + '_txt_days').text(this.opts['spacer'] + ' dagen en ')}
if(hours == 1){$(this.container + '_txt_hours').text(this.opts['spacer'] + ' uur en ');}
else{$(this.container + '_txt_hours').text(this.opts['spacer'] + ' uur en ');}
if(minutes == 1){$(this.container + '_txt_min').text(this.opts['spacer'] + ' min');}
else{$(this.container + '_txt_min').text(this.opts['spacer'] + ' min');}
if(seconds == 1){$(this.container + '_txt_sec').text(this.opts['spacer'] + '');}
else{$(this.container + '_txt_sec').text(this.opts['spacer'] + '');}
}
//end of countdown
if(days <= 0 && hours <= 0 && minutes <= 0 && seconds <= 0){
//timer is over, final output
//if date is today!
if(new Date().toDateString() == targetDate.toDateString()){
$(this.container).addClass('count_now');
$(this.container).text(this.opts['dayOf']);
}else{//if date is after today
$(this.container).addClass('count_end');
$(this.container).text(this.opts['end']);
}
this.complete = true;
}
};
/////////////////////////////////////////////////////
/////////////////////////////////////////////////////
//run immediately
this.count_update();
//now loop this every second
var selfobject = this; //scope gets lost within setInterval (see: http://www.vonloesch.de/node/32)
var theCounter = setInterval(function(){
selfobject.count_update();
if(selfobject.complete == true){
clearInterval(theCounter);}
}, 1000);
}
HTML:
$(document).ready(function() {
var aanbiedingcountdown = new BK_CountDown('#deal1', '05/25/2014', '23:57', {order: 2, spacer: ''});
var aanbiedingcountdown = new BK_CountDown('#deal2', '05/26/2014', '23:57', {order: 2, spacer: ''});
var aanbiedingcountdown = new BK_CountDown('#deal3', '05/28/2014', '23:57', {order: 2, spacer: ''});
var aanbiedingcountdown = new BK_CountDown('#deal4', '05/28/2014', '15:10', {order: 2, spacer: ''});
var aanbiedingcountdown = new BK_CountDown('#deal5', '05/26/2014', '23:57', {order: 2, spacer: ''});
});
You see, for every countdown that i want i need to create an ID.
But what i want is that when the page load, the countdown dont need to run, it makes my website slower. So, only when the someone refresh the page then he get the right date & time.
Example: Time is now 16:00u, the countdown are set at 17h, so, when someone is still on my website (10min) without refreshing the page then the countdown is still 16h only if he refresh the page then countdown is 16:10h...
I've seen this on other websites and they have more than 100 products with countdowns on the same page and still works perfect because timer is not running only if people refresh the page the the timer will set to right date & time.
Demo: http://jsfiddle.net/uJk73/ (i removed seconds, i though site will go faster without this, but no succes)
Hope someone can help my with this.
Updated jsfiddle
So let's say you had 9 deals
<div id="countdowntimer">
<div id="deal1"></div>
<div id="deal2"></div>
<div id="deal3"></div>
<div id="deal4"></div>
<div id="deal5"></div>
<div id="deal6"></div>
<div id="deal7"></div>
<div id="deal8"></div>
<div id="deal9"></div>
</div>
Get rid of this loop in BK_CountDown()
//now loop this every second
/*var selfobject = this; //scope gets lost within setInterval (see: http://www.vonloesch.de/node/32)
var theCounter = setInterval(function(){
selfobject.count_update();
if(selfobject.complete == true){
clearInterval(theCounter);}
}, 1000);
*/
Then
$(document).ready(function() {
var deals = []; // create an array
deals.push( new BK_CountDown('#deal1', '05/24/2014', '23:59', {order: 2, spacer: ''}) );
deals.push( new BK_CountDown('#deal2', '05/24/2014', '22:59', {order: 2, spacer: ''}) );
deals.push( new BK_CountDown('#deal3', '05/24/2014', '12:59', {order: 2, spacer: ''}) );
deals.push( new BK_CountDown('#deal4', '05/24/2014', '13:49', {order: 2, spacer: ''}) );
deals.push( new BK_CountDown('#deal5', '05/24/2014', '14:49', {order: 2, spacer: ''}) );
deals.push( new BK_CountDown('#deal6', '05/24/2014', '15:57', {order: 2, spacer: ''}) );
deals.push( new BK_CountDown('#deal7', '05/24/2014', '15:58', {order: 2, spacer: ''}) );
deals.push( new BK_CountDown('#deal8', '05/24/2014', '15:59', {order: 2, spacer: ''}) );
deals.push( new BK_CountDown('#deal9', '05/24/2014', '16:00', {order: 2, spacer: ''}) );
var dealcounter = setInterval(function(){ // create one setTimeout
if (deals.length){
for (i in deals){
var selfobject = deals[i];
selfobject.count_update();
if(selfobject.complete == true) delete deals[i]; // remove from array
}
}else{
clearTimeout(dealcounter); // no more to count down, stop this loop
}
}, 5000); // 5 seconds
});

adding two variables together

I have been trying for... about 4 hours now lmao.
currentCalc returns 50
currentSum returns 0 when i alert them. Yet I cannot add them together with parseInt????
what am i doing wrong :'(
var identRow = $('tr.identRow');
identRow.each(function () {
var getIdentClass = $(this).attr('class').split(' ').slice(1);
$('tr.ohp' + getIdentClass + ' td.EURm').each(function (index) {
var currentCalc = parseInt($(this).text().replace('.', ''), 10);
var currentSum = $('tr.' + getIdentClass + ' td.totalEURm', this).text().replace('.', '');
total = parseInt(currentCalc, 10) + parseInt(currentSum, 10);
$('tr.' + getIdentClass + ' td.totalEURm').text(total);
if (index == 6) {
alert(total);
}
});
});
EDIT:
Oh goodness. Im completely confused now. I putr the break there. It says total = 50.
I want each iteration to add itself to the total. That is why I add currentCalc to the text of the field im plopping the currentCalc into.
$('tr.' + getIdentClass + ' td.totalEURm').text(total);
with my code now like this:
var identRow = $('tr.identRow');
identRow.each(function () {
var getIdentClass = $(this).attr('class').split(' ').slice(1);
$('tr.ohp' + getIdentClass + ' td.EURm').each(
function (index) {
var currentCalc = parseInt($(this).text().replace('.', ''), 10) || 0;
var currentSum = parseInt($('tr.' + getIdentClass + ' td.totalEURm', this).text().replace('.', ''), 10) || 0;
var total = currentCalc + currentSum;
$('tr.' + getIdentClass + ' td.totalEURm').text(total);
if (index === 6) {
alert(total);
}
});
});
it alerts: 50, then 0, then 50, then 0.
EDIT:
How do I add currentCalc to its last value?
So first iteration its 10, seconds its 20. How do i make it so on the 2nd iteration it equals 30. currentCalc++ is just adding 1 to it.
Now you understand how crap i am :)
I am no expert in JS, but I saw that currentCalc is already an int:
var currentCalc = parseInt($(this).text().replace('.',''), 10);
//...
total = parseInt(currentCalc, 10) + parseInt(currentSum, 10);
so probably the parseInt on an int instead that on a string fails (?)
If you get two alerts, that likely means either your outer or inner .each statements is matching two entries.
If you're using firebug, use console.debug(total); instead of alert(). I recommend using console.debug(this) at some point to make sure it has what you think it has, too. Put it above the alert(). That information would be useful to see.
I do some code formatting and cleanup, try this:
var identRow = $('tr.identRow');
identRow.each(function () {
var getIdentClass = $(this).attr('class').split(' ').slice(1);
$('tr.ohp' + getIdentClass + ' td.EURm').each(
function (index) {
var currentCalc = parseInt($(this).text().replace('.', ''), 10) || 0;
var currentSum = parseInt($('tr.' + getIdentClass + ' td.totalEURm', this).text().replace('.', ''), 10) || 0;
var total = currentCalc + currentSum;
$('tr.' + getIdentClass + ' td.totalEURm').text(total);
if (index === 6) {
alert(total);
}
});
});
I added condition if parseInt fails the vars currentCalc and currentSum will be 0.
Also, like in answer above i'm avoiding double parseInt
Can you give an example html page to try out?
//SUM OF COLUMNS
var total = 0;
var identRow = $('tr.identRow');
identRow.each(function () {
var getIdentClass = $(this).attr('class').split(' ').slice(1);
$('tr.ohp' + getIdentClass + ' td.EURm').each(
function (index) {
var currentCalc = $(this).text().replace('.', '');
total = parseInt(currentCalc)+total;
$('tr.' + getIdentClass + ' td.totalEURm').text(total);
});
});
did the trick.
Now i just gotta set the total to 0 when it gets to the second category because at the moment it keeps adding from where it left off. Progress though. Thanks for everything

Categories