My code speaks for me, I want to wrap array index with another array dynamically (with a loop).
The following code does not work. Please, help me to convert this "x" string to JavaScript code or to find the right way to get the result.
var x = parentTasks[j];
while(x){
x = parentTasks + '[' + numbers + '[' + x + ']]';
}
Later "x" will become undefined, so then loop should stop.
What I expect:
Example when loop is iterated for 1st time:
parentTasks[numbers[parentTasks[j]]]
Example when loop is iterated for 2nd time:
parentTasks[numbers[parentTasks[numbers[parentTasks[j]]]]]
I did it by my self. Here is a solution:
var x = parentTasks[j];
var z = 0
while ( z++ < 2 ) {
x = 'parentTasks[numbers[' + x + ']]';
console.log(eval(x));
}
Related
I am writing JavaScript code that has a loop. There is statement in the loop:
foo = foo +1. ;
I want the code to treat foo as different variable each time the loop runs. For example:
first loop --> env.x = env.x + 2.0 ;
second loop --> env.y = env.y+ 2.0 ;
third loop --> env.z = env.z + 2.0 ;
I have looked at other solutions posted like using eval() and window() functions but still can't figure how to do this.
UPDATE: To help better understand my problem I am posting a part of the code:
if (profile.xChaos.toFixed(0) > 500.) {
if (profile.param1 == 2.0) {
profile.param1 = 0.25 ;
profile.param2 += 0.25 ;
console.log('Reset. param1 =' + profile.param1 + '; param2 increment = '+profile.param2);
}
else{profile.param1 += 0.25 ;}
profile.gui.updateDisplay({verbose : false}) ;
}
I would like to implement this in such a way that the code effectively executes these lines as:
if (profile.xChaos.toFixed(0) > 500.) {
if (profile.x == 2.0) {
profile.x = 0.25 ;
profile.y += 0.25 ;
console.log('Reset. x =' + profile.x + '; y increment = '+profile.y);
}
else{profile.x += 0.25 ;}
profile.gui.updateDisplay({verbose : false}) ;
}
where x,y can be chosen from a set of variables {profile.a, profile.b, profile.c . . .}. I hope this makes it clearer. Thanks.
Make an array of property names, then iterate over that:
const keys = ['x', 'y', 'z'];
for (const key of keys) {
env[key] = env[key] + 2.0;
}
I am trying to first get the value of the order property of an element, and then adding 1 to it when I click a button. Thing is, instead of getting 1 and adding 1 and getting 2, I get 11. Shouldn't the "+=" operator add the values? What am I doing wrong?
carouselPrev.addEventListener("click", function(){
const firstPost = document.querySelector(".blog-post");
let firstPostOrder = firstPost.style.getPropertyValue('order');
firstPost.style.order = firstPostOrder += 1;
});
Css properties are strings, and '1' + 1 = 11.
Add "+" before firstPostOrder to convert it to a number.
firstPost.style.order = +firstPostOrder += 1;
the values are strings so they are be concatenated, try parsing to an integer before using parseInt()
Try this
carouselPrev.addEventListener("click", function(){
const firstPost = document.querySelector(".blog-post");
let firstPostOrder = firstPost.style.getPropertyValue('order');
firstPost.style.order = parseInt(firstPostOrder,10) +1;
});
No, the "+=" operator is an assignment operator you'd use in lieu of "=".
let x = 42;
x += 1;
is equivalent to
let x = 42;
x = x + 1;
You want to use just the "+" to add the values, not the "+=".
I have an input field that expects a 10 digit number. If the user enters and submits a number less than 10 digits, the function would simply add a "0" until the inputed value is 10 digits in length.
I haven't really used, or understand how recursive functions really work, but I'm basically looking at an efficient way of doing this. One minor issue I'm having is figuring out how to prepend the "0"s at the beginning of the string rather than appended to the end.
My thinking:
function lengthCheck(sQuery) {
for (var i = 0; i < sQuery.length; i++) {
if (sQuery.length !== 10) {
sQuery += "0";
//I'd like to add the 0s to the beggining of the sQuery string.
console.log(sQuery);
lengthCheck(sQuery);
} else return sQuery
}
}
Change:
sQuery += "0"; // added at end of string
to:
sQuery = "0" + sQuery; // added at start of string
To remove the for loop/recursion, you could slice out the desired length in one step:
function padZeros(sQuery) {
// the max amount of zeros you want to lead with
const maxLengthZeros = "0000000000";
// takes the 10 rightmost characters and outputs them in a new string
return (maxLengthZeros + sQuery).slice(-10);
}
Simple generic function using ES6 repeat:
// edge case constraints not implemented for brevity
function padZeros(sQuery = "", maxPadding = 10, outputLength = 10) {
// the max amount of zeros you want to lead with
const maxLengthZeros = "0".repeat(maxPadding);
// returns the "outputLength" rightmost characters
return (maxLengthZeros + sQuery).slice(-outputLength);
}
console.log('padZeros: ' + padZeros("1234567890"));
console.log('padZeros: ' + padZeros("123"));
console.log('padZeros: ' + padZeros(""));
Alternate version that doesn't affect strings over your set limit:
function padZerosIfShort(inputString = "", paddedOutputLength = 10) {
let inputLen = inputString.length;
// only padded if under set length, otherwise returned untouched
return (paddedOutputLength > inputLen)
? "0".repeat(paddedOutputLength - inputLen) + inputString
: inputString;
}
console.log('padZerosIfShort: ' + padZerosIfShort("1234567890", 5));
console.log('padZerosIfShort: ' + padZerosIfShort("123", 5));
console.log('padZerosIfShort: ' + padZerosIfShort("", 5));
It will ultimately depend on your needs how you want to implement this behavior.
The += operator adds things to the end of strings similar to:
sQuery=sQuery+"0"
You can add characters to the front of a string like this
sQuery="0"+sQuery
I also found something interesting here. it works like this:
("00000" + sQuery).slice(-5)
You would add zeros to the front then slice off everything except the last 5. so to get 10 characters you would use:
("0000000000" + n).slice(-10)
You don't need recursion to solve this, just a simple for loop should do the trick. Try this:
function lengthCheck (sQuery) {
for (var i = sQuery.length; i<10; i++) {
sQuery = "0" + sQuery;
}
return sQuery;
}
You're looking to pad the string with zeroes. This is an example I've used before from here and will shorten your code a little bit:
function lengthCheck (sQuery) {
while (sQuery.length < 10)
sQuery = 0 + sQuery;
return sQuery;
}
I believe this has already been answered here (or similar enough to provide you the solution): How to output integers with leading zeros in JavaScript
I have to spreadsheets. I want the program to look at Row A on spreadsheet Ind and see if it is a 1 or 0. if it is a one on the active sheet "return" I want it to grab the date from Row D in spreadsheet "Ind" and post it onto Spreadhseet "return". I can't figure this out and I have it working on VBA in excel.
Any help would be greatly appreciated.
function myFunction() {
X = 5;
Y = 2;
Z = 1;
Count = 4560;
var ss = SpreadsheetApp.getActiveSpreadsheet();
var source_sheet = ss.getSheetByName("Ind");
var target_sheet = ss.getSheetByName("Returns");
while (Z < Count){
if (source_sheet.getRange("A" & X) = 1) {
var buydate = source_sheeet.getRange("D" & X).getValues()
target_sheet.getRange("A" & Y) = buydate
target_sheet.getRange("B" & Y) = "Buy"
Y = Y + 1
} else if (source_sheeet.Range("C" & X) = 2) {
var selldate = source_sheeet.Range("D" & X).getvalues()
target_sheet.getRange("A" & Y) = selldate
target_sheet.getRange("B" & Y) = "Sell"
Y = Y + 1
}
X = X + 1
Z = Z + 1
}}
This line:
if (source_sheet.getRange("A" & X) = 1) {
Is using an ampersand, and it should be a plus sign. To concatenate strings in JavaScript, use a plus sign.
Also, source_sheet.getRange() will return a range, not a value, so it's never going to equal 1. You would need to use something like the following:
if (source_sheet.getRange("A" + X.toString()).getValue() === 1) {
And use triple equal signs for an equality check. JavaScript is constantly attempting to coerce variables into the type that seems correct. So, it might convert the number in the variable "X" to a string, but you can also use the toString() method.
getValues() returns a two-dimensional array. Each inner array represent a row. Each element in the inner array represents a cell in a row.
If you only want to get one value, use getValue() (no "s" on the end) instead of getValues().
var buydate = source_sheet.getRange("D" + X.toString()).getValue();
You are trying to set the value by using an equal sign. That won't work. You need to use the setValue() or setValues() method.
target_sheet.getRange("A" + Y.toString()).setValue(buydate);
By not using the var key word in your assignments, the variables automatically become "global" variables.
X = 5;
Y = 2;
Z = 1;
There's no need to make them global variables in this case, I don't think.
var X = 5,
Y = 2,
Z = 1;
You can declare multiple variables all at the same time.
I need to match a substring X within string Y and need to match X then strip everything after it in Y.
Code
var text1 = "abcdefgh";
var text2 = "cde";
alert(text1.substring(0, text1.indexOf(text2)));
alert(text1.substring(0, text1.indexOf(text2) + text2.length));
First alert doesn't include search text, second one does.
Explanation
I'll explain the second line of the code.
text1.substring(0, text1.indexOf(text2) + text2.length))
text1.substring(startIndex, endIndex)
This piece of code takes every character from startIndex to endIndex, 0 being the first character. So In our code, we search from 0 (the start) and end on:
text1.indexOf(text2)
This returns the character position of the first instance of text2, in text 1.
text2.length
This returns the length of text 2, so if we want to include this in our returned value, we add this to the length of the returned index, giving us the returned result!
If you're looking to match just X in Y and return only X, I'd suggest using match.
var x = "treasure";
var y = "There's treasure somewhere in here.";
var results = y.match(new RegExp(x)); // -> ["treasure"]
results will either be an empty array or contain the first occurrence of x.
If you want everything in y up to and including the first occurrence of x, just modify the regular expression a little.
var results2 = y.match(new RegExp(".*" + x)); // -> ["There's treasure"]
You can use substring and indexOf:
Y.substring(0, Y.indexOf(X) + X.length))
DEMO
Of course you should test beforehand whether X is in Y.
var index = y.indexOf(x);
y = index >= 0 ? y.substring(0, y.indexOf(x) + x.length) : y;
var X = 'S';
var Y = 'TEST';
if(Y.indexOf(X) != -1){
var pos = parseInt(Y.indexOf(X)) + parseInt(X.length);
var str = Y.substring(0, pos);
Y = str;
}
document.write(Y);