Pushing array into array and using it throws NaN - javascript

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]));

Related

Converting time to hexidecimal then to string using javascrit

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));

javascript, getting a random number result in each singular array

I'm not sure how to word the question and i'm still quite new at javascript.
So I've got a random quote generator that has each quote result as an array. I'd like to add in two items in the array which I've got so far but having one result be a random number generated eg "2 quote" but having 2 be randomised each time. The end result is for a browser based text game. So it could be "2 zombies attack" or "7 zombies attack." The code I have so far is:
var quotes = [
[x, 'Zombies attack!'],
[x, 'other creatures attack'],
['next line'],
]
function newQuote() {
var randomNumber = Math.floor(Math.random() * (quotes.length));
document.getElementById('quote').innerHTML = quotes[randomNumber];
}
Ideally need x(or i however it's going to work) to be the result of a random number between a set range, each differently each array.
Thank you
p.s I forgot to mention that not all the quotes require a number. Thats why I've done it as a double array.
If I understand your goal correctly, you want to have a set of similar-ish message templates, pick one of them at some point and fill it with data, correct? There's a lot of ways to tackle this problem, depending on how varying can your templates be. For a simple case in my head where you just need to prepend a number to a string I'd do something like this:
var messages = [" zombies attack",
" other creatures attack"], // define your messages
messageIndex = Math.floor(Math.random() * messages.length), // pick one of them
numberOfMonsters = Math.floor(Math.random() * 10 + 1), // get your random number
result = numberOfMonsters + messages[messageIndex]; // construct a resulting message
document.getElementById('quote').textContent = result;
If you'd rather have more complex strings where you don't necessarily add a number (or any string) to the beginning, like ["There's X things in the distance", "X things are somewhere close"], then I'd recommend to either come up with some sort of string formatting of your own or use a library to do that for you. sprintf.js seems to be just right for that, it will let you do things like this:
var messages = ["%d zombies attack",
"A boss with %d minions attacks"], // define your messages
messageIndex = Math.floor(Math.random() * messages.length), // pick one of them
numberOfMonsters = Math.floor(Math.random() * 10 + 1), // get your random number
result = sprintf(messages[messageIndex], numberOfMonsters) // format a final message
document.getElementById('quote').textContent = result;
EDIT: Your task is much more complex than what is described in the original question. You need to think about you code and data organization. You have to outline what is finite and can be enumerated (types of actions are finite: you can loot, fight, move, etc.), and what is arbitrary and dynamic (list of monsters and loot table are arbitrary, you have no idea what type and amount of monsters game designers will come up with). After you've defined your structure you can come up with some quick and dirty message composer, which takes arbitrary entities and puts them into finite amount of contexts, or something. Again, I'm sort of shooting in the dark here, but here's an updated version of the code on plunkr.
I solved it to do what I want and still have the numbers different. The issue was I should have had the number generator within the quote function. Also can create multiple variables to use too for different number generators. The plan is to then integrate it with php to add content dynamically. Which I can do. Thanks Dmitry for guiding me in the right direction.
function newQuote() {
var MonsterOne = Math.floor((Math.random() * 14) + 0);
var MonsterTwo = Math.floor((Math.random() * 14) + 0);
var MonsterThree = Math.floor((Math.random() * 14) + 0);
var MonsterFour = Math.floor((Math.random() * 14) + 0);
var quotes = [
['Test', MonsterOne, 'One'],
['Test', MonsterOne,'Two'],
['Test', MonsterThree, 'Three'],
[MonsterFour, 'Four'],
['Five'],
]
var randomNumber = Math.floor(Math.random() * (quotes.length));
document.getElementById('quote').innerHTML = quotes[randomNumber];
}

Jquery convert object to string and slice

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);

Is there any other way to put some arrays together and be able to call only one element of them randomly?

I need to grab the elements of some small arrays and put them together to make a bigger array. But I don't want those small arrays to be the elements of the big array. I just need their elements. Then I need to randomly chose ONLY one element from the big array.
Normally the big array will be:
Array.prototype.randomElement = function () {
return this[Math.floor(Math.random() * this.length)]
}
var small_1_array = [1,2,3,4];
var small_2_array = [5,6,7,8,9];
var small_3_array = [10,11,12];
var big_array = [small_1_array, small_2_array, small_3_array];
console.log("big_array is: " + big_array);
Result:
big_array is: 1,2,3,4,5,6,7,8,9,10,11,12
The problem with this way is that I can only choose one of the the small arrays(a group of numbers), but not their elements(only a number). For example:
console.log("a random number from big_array is: " + big_array.randomElement());
Result:
a random number from big_array is: 1,2,3,4
And this is a solution I could think of:
var rearrange_array = (big_array.toString()).split(",");
console.log("rearrange_array is : " + rearrange_array);
Result:
rearrange_array is : 1,2,3,4,5,6,7,8,9,10,11,12
Now if I execute:
console.log("a random number from rearrange_array is: " + rearrange_array.randomElement());
the result would be something like this:
a random number from rearrange_array is: 2
Is there any other way to put some arrays together and be able to call only one element of them?
Just apply your randomElement function twice:
console.log("a random number from one of the arrays is: "
+ big_array.randomElement().randomElement());
Of course you also could put the small arrays together and choose from the new huge one. The method to do that is concatenation:
var rearrange_array = Array.prototype.concat.apply([], big_array);
// or, without the big_array variable:
var rearrange_array = small_1_array.concat(small_2_array, small_3_array);
// then:
return rearrange_array.randomElement();
Use Array.concat, which
Returns a new array comprised of this array joined with other array(s) and/or value(s).
In your case:
var small_1_array = [1,2,3,4];
var small_2_array = [5,6,7,8,9];
var small_3_array = [10,11,12];
var big_array = small_1_array.concat(small_2_array, small_3_array);
console.log("a random number from big_array is: " + big_array.randomElement());

Append an integer to a string name

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.

Categories