I'm trying to get my for loop to show every number between 47 to 28 in order highest to lowest.
For some reason my code gives me the answer "28, 28".
Can anyone help me se what I've done wrong? I just want to add that I'm still very new to javascript!
var fx = "";
var printRangeReversed = function(rangeStart1,rangeStop1){
for (var a3=rangeStart1; a3 > rangeStop1; a3--);
fx+=a3+",";
return fx=rangeStop1&&(fx+=a3),fx;
return fx = fx.substr(0,fx.length-1);
}
ANSWER = printRangeReversed(47,28);
The for loop ends with a ;, so the subsequent line is just executing as if it were outside the loop. Also, the second return statement is redundant, as the code below the first return is unreachable.
A better code would be
var fx = "";
var printRangeReversed = function(rangeStart1,rangeStop1){
var arr = [];
for (var a3 = rangeStart1; a3 >= rangeStop1; a3--)
arr.push(a3);
return arr.join(); // same as arr.join(",")
}
fx = printRangeReversed(47, 28);
Note, that I've used >= instead of just >, as it isn't what you want.
You don't want to do a return inside the loop. Let it finish, then return the result. For example:
var printRangeReversed = function(rangeStart1,rangeStop1){
var fx = "";
for (var a3=rangeStart1; a3 > rangeStop1; a3--) {
fx+=a3+",";
}
return fx;
}
ANSWER = printRangeReversed(47,28);
Related
First of all, I'm a total beginner in coding and have started a few weeks back, as an persona/intellectual challenge.
I want to know why do I get a null array in this simple script. I think it has something to do with var "i", but I can't find where the error is.
function DivEsc() {
var ssIn = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Input");
var ssOut = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Output");
var esc = ssIn.getRange(1,3).getValue(); //Escaños en reparto
var i = 0;
var arr = [400, 200,100,50];
var newArr = []
newArr = arr.forEach(num => {
for (var i = 1; i <= esc; i++){
return (num/i)
// newArr.push(num)
}
newArr.push(num/i)
}
)
Logger.log(newArr)
}
Array.prototype.forEach does not return a value, newArr will therefore become undefined. JavaScript is a dynamic language where the reassignment of values - even if they don't have the same type - is possible.
Further you return in the first iteration of the for loop, meaning that only the value for num / 1 will be calculated; probably not what you want.
// newArr is now undefined!
newArr = arr.forEach(num => {
for (var i = 1; i <= esc; i++){
// If you return a value here, the loop will stop after the first round with i = 1!
return (num/i)
// newArr.push(num)
}
newArr.push(num/i)
}
)
You could just directly push into newArr to make it work.
arr.forEach(num => {
for(var i = 1; i <= esc; i++) {
newArr.push(num / i);
}
)
If you want to learn more to try out different ways to implement your algorithm, look into JavaScript's functional array methods as e.g. Array.prototype.map and Array.prototype.reduce.
On a side note: Try using an editor/IDE that handles formatting code for you. In your snippet the formatting (e.g. end of the forEach call) makes it hard to reason about the code.
var a = "gsdgtrshghf";
function reverseString(strr){
if (!strr.length){
var result="";
for(var i=strr.length;i>0;i++){
var a=strr.chatAt(i);
result+=a;
}
}return result;
}
console.log(reverseString(a))
When I tried to run it it returned me "undefined". I wonder what's the problem here.
The main reason is you are declaring var result="" and returning from outside of if(so it become undefined as its scope is only inside if statement) and other errors areas mention in comments you have a typo, charAt not chatAt. You can also simply use strr[i] to get the char. Also, you should do i-- and i >= 0 if you start at strr.length, otherwise for loop is immediately completed at the condition check. Check the below code.
var a = "gsdgtrshghf";
function reverseString(strr){
var result="";
if (strr.length){
for(var i=strr.length-1;i>=0;i--){
var a=strr.charAt(i);
result+=a;
}
}
return result;
}
console.log(reverseString(a))
Have a look:
var a = "gsdgtrshghf";
function reverseString(strr) {
var result = "";
if (strr.length != null) {
for (var i = strr.length - 1; i >= 0; i--) {
var a = strr.charAt(i);
result += a;
}
}
return result;
}
console.log(reverseString(a));
// Better
const reverse = str => Array.from(str).reverse().join('');
console.log(reverse('foo 𝌆 bar mañana mañana'));
Explanation
It's charAt(i) not chatAt(i)
Loop should start from length - 1 and end at 0 and i should be decremented
And finally declare the variable outside of if
i.e for(var i = strr.length - ; i >= 0; i--){
not for(var i=strr.length;i>0;i++){
Better yet, use combo of Array.from(str).reverse().join(''), as it even works with Unicode characters, as pointed out in comments by gaetanoM
hey guys i wrote a function that compares array values and returns the minimum value but i want to know if there are ways to make it more efficient like iterating through all arrays (using one loop) and putting the results in a new array or making individual arrays sub-arrays of a single array, etc. Also the function provides the correct output but prints the answer three times:
var nums1 = [-7528819, 3927361, -6398192];
var nums2 = [1777100, -2299720, -5566643];
var nums3 = [7188445, 3724971, 7699332];
var nums4 = [-8432528, -159836, -1604959];
var nums5 = [2764889, 4681472, 701396];
var nums6 = [-5073513, 599535, 4388457];
var nums7 = [8689640, 8028586, 1022322];
var nums8 = [-1088592, 1211232, -7868192];
var nums9 = [-5848613, -4945165, 631213];
var nums10 = [3218429, -833619, -1495854];
var nums11 = [8007060, 1637562, -7568493];
var nums12 = [-8391131, -6585338, 131787];
var nums13 = [-3957775, -9396892, -6143241];
var nums14 = [-6258442, -7829421, 3696922];
var nums15 = [2136598, 4935467, -1621605];
var nums16 = [-7162005, 9861954, 8977930];
var nums17 = [7226452, 8551594, 7006517];
var nums18 = [-1751226, -2536997, -1782251];
var nums19 = [380582, 1614389, 3272584];
var nums20 = [-8988205, -5167181, -7561034];
var nums21 = [-484059, -7160121, 4076528];
var nums22 = [1947448, -5551253, 7491190];
var numsLength = nums1.length;
var i = 0;
var minNum;
function test(arr) {
for (i; i < numsLength; i++) {
if (arr[0] < arr[1] && arr[2]) {
minNum = arr[0];
} else if (arr[1] < arr[2] && arr[0]) {
minNum = arr[1];
} else if (arr[2] < arr[1] && arr[0]) {
minNum = arr[2];
}
console.log(minNum);
}
}
test(nums1);
You could just use Math.min function.
console.log(Math.min.apply(null, nums1));
Look at his snippet of code and read inline comments:
var nums = [];
// I'm pushing only 3 sets of data, but there can be any number
// Also there can be any number of elements in each array as you can see
nums.push([-7528819, 3927361, -6398192]);
nums.push([1777100, -2299720, -5566643, 380582]);
nums.push([7188445, 3724971, 7699332, 1947448, -5551253, 7491190]);
function produceResults(nums) {
var i,
results = [];
// gathering results
for (i = 0; i < nums.length; i++) {
results.push(Math.min.apply(null, nums[i]));
}
return results;
}
console.log(produceResults(nums));
So 2 suggestions:
use more dynamic structure (array of arrays) instead of
defining 22 arrays.
use built in JS functions and components (Math.min)
Unrolling a loop is actually the most efficient implementation of a loop in most cases. However, practically speaking, unrolling a loop isn't usually feasible. With a small, fixed-size array, like those you have here, each permutation of the loop is obvious, and if your goal is raw speed you can't get much more efficient than what you have. That being said, the loop in your function is useless, as others have pointed out., because you've essentially unrolled the loop already. Also the syntax of the if statement is incorrect, and you are not handling the case where values in the array are equal. For fixed arrays of size three you want something more along the lines of...
if (val1 <= val2 && val1 <= val3) {
minVal = val1;
} else if (val2 <= val1 && val2 <= val3) {
minVal = val2;
} else minVal = val3;
Now if you want to do an arbitrary search for the min value of any size array you would do something similar, but using a loop, like...
var minVal = null;
for (var i = 0; i < arr.length; i++) {
if (minVal === null || minVal > (val = arr[i]))
minVal = val;
}
Depending on what you actually want to accomplish, and the size of the array, it might make sense to sort the array and rerurn the min (0 index) from the sorted array. If you go that route, start with a google search for "sort algorithms"
I've written a function that takes plevel (integer) and slevel (array of strings of numbers) and finds the smallest difference between plevel and a value in slevel. However, when I run the script, it is unresponsive and the debugger says that diff is undefined.
var findDiff = function findDiff(plevel, slevel) {
var diff = new Array();
for (i=0; i<=slevel.length; i++) {
sleveli = parseInt(slevel[i]);
diff.push(Math.abs(plevel-sleveli));
}
if (diff.length > 1){
diff.sort(function(a, b){return a-b});
return diff[0]
}
else{
return diff[0];
}
}
The function is invoked here:
var matches = new Array();
var newFetch = Data.find().fetch();
for(i = 0; i <= newFetch.length; i++ ){
pointsMatch = 0
var difference = findDiff(newFetch[i].level, spec.level);
pointsMatch -= (difference*3);
matches.push([newFetch[i], pointsMatch])
}
console.log(matches)
Data is a mongoDB collection. spec.level is an array of strings of numbers stored as a property in an object.
I would like to point out name space pollution, which may cause serious troubles. In my understanding, you have two cases of namespace pollution, one of it creates an endless loop.
You have actually an inner an outer loop, separated by a function. Your outer for loop:
for(i = 0; i <= newFetch.length; i++ ){
pointsMatch = 0
...
And then your inner for loop:
for (i=0; i<=slevel.length; i++) {
sleveli = parseInt(slevel[i]);
...
Because of the missing var before i, both for loop definitions are actually like this:
for (window.i=0; ...
So the inner loop overwrites the variable i the outer loop depends on to terminate. i is "polluting" namespace.
The second case is harmless:
sleveli = parseInt(slevel[i]);
Because of the missing var, this results in fact in
window.sleveli = parseInt(slevel[i]);
Better would be
var sleveli = parseInt(slevel[i]);
But this is a time bomb.
I suggest you add var to the definitions of i in the for loop.
I think the people in the comments are right; we need to see some more of your input to debug this properly. But you can simplify your code a lot by tracking the mins as you go:
var findDiff = function findDiff(plevel, slevel) {
var min = Number.MAX_SAFE_INTEGER;
for (i=0; i<slevel.length; i++) {
sleveli = parseInt(slevel[i]);
var diff = Math.abs(plevel-sleveli);
min = Math.min(min, diff)
}
return min;
}
var a = ["1", "2", "10", "17"]
var p = 6
// We're expecting 4 as the min diff
console.log(findDiff(p, a))
// ...prints out 4 :-)
http://repl.it/ceX
As Omri points out, use < not <= in your for loop.
Note - Number is not always available -- see here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER
You could alternatively set the initial min to something suitably large for your likely data, like 2^10
Can someone explain why this for...loop doesn't work? (it should write all checked checkboxes but it writes only the last checked)
function Matula()
{
var x = document.getElementsByTagName("body")[0];
var y = document.createElement("p");
var g = document.createTextNode("Vasa pizza bude obsahovat:");
y.appendChild(g);
x.appendChild(y);
var swag = document.forms["lol"].matej.length;
for (var i = 0; i < swag; i++)
{
if (document.forms["lol"].matej[i].checked)
{
var torko = document.getElementsByTagName("body")[0];
var q = document.createElement("p");
var w = document.createTextNode(document.forms["lol"].matej[i].value);
q.appendChild(w);
torko.appendChild(q);
return mocny = 0
}
};
}
return mocny = 0
exits the function , so for it loops only once, put it outside for loop
There is a return statement in your if block. This will essentially break the loop after the first time it goes inside the if. So that means only value of one check box will be print out.
I have no idea as to what that is supposed to do as it is awfuly confusing will all those var names. But your return inside your if, which inside your for loop, doesn't seem right.
You should put that at the last line of your function.
A cleaner code could look like this:
function Matula() {
var body = document.body;
addParagraph(body, "Vasa pizza bude obsahovat:");
var allToppings = document.forms["lol"].matej;
var toppingsCount = allToppings.length;
for (var i = 0; i < toppingsCount; i++) {
if (allToppings[i].checked) {
addParagraph(body,allToppings[i].value);
}
}
}
function addParagraph(body, textToAdd) {
var p = document.createElement("p");
p.appendChild(textToAdd);
body.appendChild(y);
}
Typed off my head, might contain typos
Makes it so much easier to read. Btw. Bracket position does make a difference (it isn't Java), so keep it on the same line (Google the reasons) Does it work for you?