Why is this for loop not logging sum? [closed] - javascript

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am trying to use this for loop within the function to get the sum of an array. However, when I call the function I receive NaN.
tips = [1,2,3,4,5]
function sumTip (tips){
for (i=0; i<tips.length; i++){
var total = total + tips[i];
console.log(total);
}
}
sumTip();

Error 1 - Wrong syntax. It should be tips.length and not length.tips.
Error 2 - You haven't given the parameter to the function when you
are calling it. It should be sumTip(tips);
Error 3 - i is not declared in the loop.
Error 4 - For your logic to work, the total should be declared and initialised to zero outside the for loop and then used inside the loop.
You are doing - var total = total + tips[i]; when total hasn't been defined yet so the in the expression total + tips[i] evaluates to NaN and that's why you are getting Nan as output.
The following code should work after correcting the above mentioned errors -
tips = [1,2,3,4,5]
function sumTip (tips){
var total = 0;
for (var i=0; i<tips.length; i++){
total = total + tips[i];
console.log(total);
}
}
sumTip(tips);

Couple problems you're running into here. First, in your last line, when you call sumTip, you never pass it the array, like: sumTip(tips). Second, you are resetting total everytime you loop, it should be set up like:
var total = 0;
for (var i=0; i<tips.length; i++){
total += tips[i];
console.log(total);
}
This all could just be reduced though: let sum = tips.reduce((a, b) => a + b, 0)

Related

tried reverse array but reverse last item instead [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I tried to reverse array items, but it reverse the last item not array. I also posted the expected output. Hope it will make easy to understand.
var color = ("red", "green", "blue");
function printReverse(str) {
for (var i = str.length - 1; i >= 0; i--) {
console.log(str[i]);
}
}
printReverse(color);
/*
output
e
u
l
b
*/
You define arrays with this statement: ["red","green","blue"], not this: ("red","green","blue"):
var color = ["red","green","blue"];
function printReverse(str){
for ( var i = str.length-1; i>= 0; i-- ){
console.log(str[i]);
}
}
printReverse(color);
var color = ["red","green","blue"];
var rev_color = color.reverse()

Unexpected behaviour with for in a nodelist [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I have a nodelist with 30 divs and I need to include 1 div every 4 divs but the var 'c' does not change and stack all the divs in the position[6].
for (i = 0; i < 8; i++) {
var pub = "pub-retangulo-";
var c = 2;
c += 4;
var o = document.createElement("div");
o.setAttribute("id", pub.concat(i.toString()));
o.setAttribute("align", "center");
var container = document.querySelectorAll(".short-summary")[c];
container.parentNode.insertBefore(o, container);
}
You are redeclaring your c variable at each iteration. That is why is it stuck at 6. You need to move this assignation outside your loop
var pub = "pub-retangulo-";
var c = 2;
for (i = 0; i < 8; i++) {
var o = document.createElement("div");
o.setAttribute("id", pub.concat(i.toString()));
o.setAttribute("align", "center");
var container = document.querySelectorAll(".short-summary")[c];
container.parentNode.insertBefore(o, container);
c += 4;
}
I've also moved your c+=4 at the end of the loop, this will cause the loop to execute at c = 2 the first time rather than c = 6
As Barmar said, you might not need a variable at all in this case. You are incrementing by four each time, so you could replace your c variable with 2 (initial value) + i(current iteration index) * 4 (increment ratio).
P.S. This code is UNTESTED, please don't just copy and paste it expecting everything to work perfectly. Try to understand it and apply it to your own context.

Having trouble with getElementsByTagName(blockquote) [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I am trying to get it to return "ha, awesome" followed by the index of the word "awesome"
HTML:
<blockquote id = "blocky">
ha, awesome<br>
</blockquote>
JS:
var x = document.getElementsByTagName(blockquote).innerHTML ;
var n = x.indexOf("awesome");
document.getElementsByTagName(blockquote).innerHTML = x + "<br>" + n;
If I change the JS to this, it works
var x = document.getElementById("blocky").innerHTML ;
var n = x.indexOf("awesome");
document.getElementById("blocky").innerHTML = x + "<br>" + n;
https://jsfiddle.net/mzrt/zaf98g8y/1/
First off, you need to pass it a string, not a variable (unless that variable contains a string).
var x = document.getElementsByTagName('blockquote');
Next, document.getElementsByTagName returns a element collection, not a single element. You can get the first result using [0].
var x = document.getElementsByTagName('blockquote')[0];
Or you can iterate through all of the elements using a for loop.
for (var i = 0; i < x.length; i++) {
var element = x[i];
element.innerHTML = '...';
}
Basically getElementsByTagName will return a node list, an array like object, you cannot access the property of a node from it directly, you have to use bracket notation to fetch the first node from it and then you can treat it as a node object,
var x = document.getElementsByTagName('blockquote')[0].innerHTML;
Since the element that you are targeting is an element with id, It is better to go with getElementById.
var x = document.getElementsByTagName('blockquote')[0].innerHTML ;
var n = x.indexOf("awesome");
document.getElementsByTagName('blockquote')[0].innerHTML = x + "<br>" + n;
Get element by tag name returns a node list, so you have to tell whitch node you do want.
Also you should pass tagname between single quotes.

Recursive Call and Function Definition [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I am attempting to implement what should be a simple coding interview-like question. However, I'm having difficulty making the recursive call:
(function () {
if(typeof Algorithms === "undefined") {
window.Algorithms = {};
}
// Write a method, digital_root(num).
// It should sum the digits of a positive integer.
// If it is greater than or equal to 10, sum the digits of the resulting number.
// Keep repeating until there is only one digit in the result, called the "digital root".
// Do not use string conversion within your method.
Algorithms.digitalRoot = function (number) {
if (number < 10) {
return number;
}
var sum = 0;
while(number != 0) {
sum += number % 10;
number = Math.floor(number/10);
}
this.digitalRoot(sum);
};
The spec looks like so:
it("65,536 should return 7", function() {
expect(Algorithms.digitalRoot(65536)).toBe(7);
});
it("1,853 should return 8", function() {
expect(Algorithms.digitalRoot(1853)).toBe(8);
});
I thought what happened was: Algorithms is an object that has digitalRoot as a property (specifically a function). Thus, when Algorithms.digitalRoot(number_here) is called, the this should refer to Algorithms. Therefore, I wrote the recursive call like this.digitalRoot(sum). Could someone please correct my incorrect thinking?
The error reads as below:
digitalRoot 65,536 should return 7. Expected undefined to be 7. Error:
Expected undefined to be 7.
at new jasmine.ExpectationResult (file:///C:/Users/Documents/GitHub/practice-thy-algorithms/Javascript/lib/jasmine-1.3.1/jasmine.js:114:32)
at null.toBe (file:///C:/Users/Documents/GitHub/practice-thy-algorithms/Javascript/lib/jasmine-1.3.1/jasmine.js:1235:29)
at null. (file:///C:/Users/Documents/GitHub/practice-thy-algorithms/Javascript/spec/algorithms_spec.js:3:43)
at jasmine.Block.execute (file:///C:/Users/Documents/GitHub/practice-thy-algorithms/Javascript/lib/jasmine-1.3.1/jasmine.js:1064:17)
at jasmine.Queue.next_ (file:///C:/Users/Documents/GitHub/practice-thy-algorithms/Javascript/lib/jasmine-1.3.1/jasmine.js:2096:31)
at jasmine.Queue.start (file:///C:/Users/Documents/GitHub/practice-thy-algorithms/Javascript/lib/jasmine-1.3.1/jasmine.js:2049:8)
at jasmine.Spec.execute (file:///C:/Users/Documents/GitHub/practice-thy-algorithms/Javascript/lib/jasmine-1.3.1/jasmine.js:2376:14)
at jasmine.Queue.next_ (file:///C:/Users/Documents/GitHub/practice-thy-algorithms/Javascript/lib/jasmine-1.3.1/jasmine.js:2096:31)
at jasmine.Queue.start (file:///C:/Users/Documents/GitHub/practice-thy-algorithms/Javascript/lib/jasmine-1.3.1/jasmine.js:2049:8)
at jasmine.Suite.execute (file:///C:/Users/Documents/GitHub/practice-thy-algorithms/Javascript/lib/jasmine-1.3.1/jasmine.js:2521:14)
You don't return anything from your function unless number < 10. That is why you are getting undefined instead of 7. Your expectation about this was correct.
Return the value this.digitalRoot(sum);:
...
number = Math.floor(number/10);
}
return this.digitalRoot(sum);
};

Sum of elements, differences between code [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I have two pieces of code both calculating the sum of the elements of an array:
var sum = array.reduce(function(previousValue, currentValue) {
return previousValue + currentValue;
}, 0);
or
var sum = 0;
array.forEach(function(e) {
sum += e;
});
Are there any differences between them beside different implementations? When is it better to use which one?
Besides your personal style preference, there could be also difference in actual performance. Those two look to perform similarly however.
If you're doing this operation a lot (or for large arrays) consider using the third way:
var sum = 0;
for (l = array.length; l--; ) { sum += array[l]; }
This will be way faster. Check this performance test for actual results.
Note: you will gain some speed if you cache array length. So instead of doing this:
for (var i = 0; i < array.length; i++) {...}
Do this:
var l = array.length;
for (; l--; ) { ... }
or this:
for (l = array.length; l--;) { ... }
First one is slightly heavier than the second one.
The fastest way is to avoid calling functions for each step and use loops like for.
var sum = 0;
for(var i=0, len=array.length; i<len; i++){
sum += array[i];
}
as using both of these function involves executing the callback function for each element that would incur the function calling overhead (so both re not efficent), using loop will give better performance.

Categories