Hi Im trying to iterate through a for loop from a long string of words held in a single string(wordlist), within impactjs:
var wordlist3 ="hellwhentrysthisbreaks"
var xc=3;
var word_length = 4;
var words_in_round = 4;
for ( i=0; i<words_in_round; i++){
var num_words = ['wordlist' + xc].length / word_length;
var random = Math.floor(Math.random() * ((num_words+1) - 0 ));
n = Math.round(random / word_length) * word_length;
random_word =(['wordlist' + xc].substring(n,(n+word_length)))
random_words += random_word;
}
The above code works if i define wordlist as a global, but when i made it local num_words is not defined properly and random word throws this object has no method substring ..
My problem is, that since i converted to local variables when i append the string name and call .length it gives me the length of the new name (wordlist3.length = 9) instead of the length of wordlist3 =20 .. also i cant call the method substring on this object ...
['wordlist' + xc].substring
will NEVER work (well, unless it's preceded by another variable, eg. foo['wordlist' +xc].substring). This is because, in Javascript [anything] means "an array of 'anything'", and (as Kendall mentioned) arrays do not have a substring method.
try:
random_word =(('wordlist' + xc).substring(n,(n+word_length)))
instead.
Related
I am trying to convert present time to hexidecimal then to a regular string variable.
For some reason I can only seem to produce an output in double quotes such as "result" or an object output. I am using Id tags to identify each div which contains different messages. They are being used like this id="somename-hexnumber". The code if sent from the browser to a node.js server and the ID is split up into two words with first section being the person's name then "-" is the split key then the hexidecimal is just the div number so it is easy to find and delete if needed. The code I got so far is small but I am out of ideas now.
var thisRandom = Date.now();
const encodedString = thisRandom.toString(16);
var encoded = JSON.stringify(encodedString);
var tIDs = json.name+'-'+encoded;
var output = $('<div class="container" id="'+tIDs+'" onclick="DelComment(this.id, urank)"><span class="block"><div class="block-text"><p><strong><'+json.name+'></strong> '+json.data+'</p></div></div>');
When a hexidecimal number is produced I want the output to be something like 16FE67A334 and not "16FE67A334" or an object.
Do you want this ?
Demo: https://codepen.io/gmkhussain/pen/QWEdOBW
Code below will convert the time/number value d to hexadecimal.
var thisRandom = Date.now();
function timeToHexFunc(x) {
if ( x < 0) {
x = 0xFFFFFFFF + x + 1;
}
return x.toString(16).toUpperCase();
}
console.log(timeToHexFunc(thisRandom));
I've got a variable called colorHM:
var colorHM = "50,50,74,255,100,255,4,3,50".
Now I'm using this snippet here to cut it into pieces with the following scheme: R,g,b,R,g,b,R,g,b, and again to var a = R,g,b and var b = R,g,b etc...
var firstColorHM = colorHM.split(",", 3);
firstColorHM = firstColorHM.toString();
var firstColorHMA = firstColorHM.split(",");
firstCMA.push(firstColorHMA[0]);
firstCMA.push(firstColorHMA[1]);
firstCMA.push(firstColorHMA[2]);
But using it to calculate distance = eDist(firstCMA, firstCTA) gives me NaN.
function eDist (col1, col2) {
var rmean = ((col1[0] + col2[0]) / 2);
var dR = (col1[0] - col2[0]);
var dG = (col1[1] - col2[1]);
var dB = (col1[2] - col2[2]);
return Math.sqrt((2 + (rmean / 256)) * Math.pow(dR, 2) + (4 * Math.pow(dG, 2)) + ( 2 + ((255- rmean) / 256)) * Math.pow(dB, 2));
}
Using firstCMA.push(10); firstCMA.push(20); firstCMA.push(30); instead of firstCMA.push(firstColorHMA[0]);.. makes it work again.
The variable firstCTA is left out, but parsed the same way.
I simply checked if the Arrays were working by trying to call different indexes from the array, which worked.
Why does pushing numbers work but pushing firstColorHMA[0] doesnt?
Thanks in advance!
Like the comments says, when you split() a string, the generated array will contain strings:
The split() method splits a String object into an array of strings by separating the string into substrings, using a specified separator string to determine where to make each split.
So actually the array firstColorHMA holds numbers as strings, an easy fix to this, will be using the unary plus to cast the array items to numbers, like this:
firstCMA.push(+firstColorHMA[0]);
firstCMA.push(+firstColorHMA[1]);
firstCMA.push(+firstColorHMA[2]);
Or alternatively, use a more explicit logic like:
firstCMA.push(Number(firstColorHMA[0]));
firstCMA.push(Number(firstColorHMA[1]));
firstCMA.push(Number(firstColorHMA[2]));
Here's the situation:
function STP() { var LOC = window.location.href;
var CSV = LOC.substring(LOC.indexOf(',')+1);
var ARR = CSV.split(',');
var STR = ARR[ARR.length -1 ];
var POS = window.document.getElementById(STR).offsetTop;
alert( STR ); };
Explained:
When the page loads, the onload calls the script.
The script gets the location.href and Extracts the element ID by
creating an array and referencing the last one.
So far so good.
I then use that to reference an element ID to get its position.
But it doesn't work.
The STR alert indicates the proper value when it's placed above POS, not below. The script doesn't work at all below that point when the STR var reference is used.
However if I do a direct reference to the ID ('A01') no problem.
Why does one work and not the other when both values are identical? I've tried other ways like using a hash instead of a comma and can extract the value that with .location.hash, but it doesn't work either.
The problem is that when you do
LOC.substring(LOC.indexOf(',') + 1);
you're putting everything after the , into the CSV variable. But there is a space between the comma and the 'A01'. So, the interpreter reduces it to:
var POS = window.document.getElementById(' A01').offsetTop;
But your ID is 'A01', not ' A01', so the selector fails.
function STP() {
var LOC = 'file:///M:/Transfers/Main%20Desktop/Export/USI/2018/Catalog/CAT-Compilations-01a.htm?1525149288810, A01';
var CSV = LOC.substring(LOC.indexOf(',') + 1);
var ARR = CSV.split(',');
var STR = ARR[ARR.length - 1];
console.log(`'${STR}'`);
}
STP();
To solve this, you can increase the index by one:
LOC.substring(LOC.indexOf(',') + 2);
But it would probably be better not to put spaces in URLs when not necessary - if possible, send the user to 'file:///M:/Transfers/Main%20Desktop/Export/USI/2018/Catalog/CAT-Compilations-01a.htm?1525149288810,A01' instead.
I'm getting the following error in my app's script when replacing strings in a template file to generate reports.
Index (-1) value must be greater or equal to zero.
The function is listed bellow.
/**
* Search a String in the document and replaces it with the generated newString, and sets it Bold
*/
function replaceString(doc, String, newString) {
var ps = doc.getParagraphs();
for(var i=0; i<ps.length; i++) {
var p = ps[i];
var text = p.getText();
//var text = p.editAsText();
if(text.indexOf(String) >= 0) {
//look if the String is present in the current paragraph
//p.editAsText().setFontFamily(b, c, DocumentApp.FontFamily.COMIC_SANS_MS);
p.editAsText().replaceText(String, newString);
// we calculte the length of the string to modify, making sure that is trated like a string and not another ind of object.
var newStringLength = newString.toString().length;
// if a string has been replaced with a NON empty space, it sets the new string to Bold,
Logger.log([newString,newStringLength]);
if (newStringLength > 0) {
// re-populate the text variable with the updated content of the paragraph
text = p.getText();
Logger.log(text);
p.editAsText().setBold(text.indexOf(newString), text.indexOf(newString) + newStringLength - 1, true);
}
}
}
}
When it errors out
[newString,newStringLength] = [ The Rev Levels are at ZGS 003 on the electric quality standard. The part has a current change to ZGS 005!,108]
Does anyone have any suggestions?
Thanks in advance,
Michael
You are not handling the case where the string isnt there. Thus indexOf returns -1 and you use that. Also dont use reserved words like String for variable names.
Via ajax-based script i get object:
for example:
item.TYP_PCON_START
which value is, for example 201212...
When i try to slice him, i get oject error...
How could i slice this object so, that for example i get 2012, or better set two last numbers on furst place and add dot, like:
12.2012
How could i do this? (i append this text as value of select list)
You need to slice the string property, not the object itself:
item.TYP_PCON_START.slice(-2) + '.' + item.TYP_PCON_START.slice(0, 4);
> '12.2012'
http://jsfiddle.net/4Hdme/
edit: In the case that your property is a number, you must convert it to a string before attempting to slice it:
var propertyAsString = item.TYP_PCON_START.toString();
propertyAsString.slice(-2) + '.' + propertyAsString.slice(0, 4);
> '12.2012'
http://jsfiddle.net/4Hdme/1/
var a = item.TYP_PCON_START,
a = a+"",
a = a.split("");
a.splice(2,0,".");
a = a.join("");
a = parseFloat(a);
console.log(a);