Confusion about assignment with commas - javascript

What is the logic behind the following code?
var next, output = null, thisNode;
It appears like it's some type of coalescing like var foo = bar || baz;, but I'm not so familiar with the commas.

It's just a shorter way of writing:
var next;
var output = null;
var thisNode;

multiple variable declarations.
its the same as this:
var next;
var output = null;
var thisNode;

Related

unable to print result line by line

I am unable to print result in line by line,it's coming in one line ,how to solve this....
I tried this code-
<script>
function know(){
var num =Number(document.getElementById('number').value);
var range=Number(document.getElementById('range').value);
var output="";
var final=[];
for(i=1;i<=range;i++)
{output=i*num;
final.push(output)
final=final.replace(",","<br/>")}
document.getElementById('result').innerHTML=final
}
</script>
There is 2 issues in it:
the for loop i you need to declare as a var or let(I recommend let)
there is no replace method in array, you can use map in this case
So you can re write the method like this.
<script>
function know(){
var num =Number(document.getElementById('number').value);
var range=Number(document.getElementById('range').value);
var output="";
var final=[];
//for(i=1;i<=range;i++)
for(let i=1;i<=range;i++)
{output=i*num;
final.push(output)
//final=final.replace(",","<br/>")
}
final = final.map((d, ind) => d*(ind+1))
document.getElementById('result').innerHTML=final
}
</script>

How to get json data with vars in p5.js

I'm building a dictionary word definition search engine which has a #submit button and #word input. I also have a JSON dictionary(Github link). I don't know how to select what word definition to use depending on what the user types.
I have already tried putting the input.value() as a var to the json object query:
var uInVal = input.value();
document.getElementById("p1").innerHTML = words.uInVal)
Can someone help me?
My Code:
var words;
var input;
function setup() {
loadJSON("dictionary.json", gotData);
var button = select('#submit');
button.mousePressed(keyDraw);
input = select('#word');
}
function gotData(data){
words = data;
}
function keyDraw(){
document.getElementById("p1").innerHTML; //This is where the word definition should get printed
}
In the future, please try to work with a simpler example. Something like this would show your problem in a runnable example:
var jsonString = '{"x": 42, "y":100}';
var jsonObject = JSON.parse(jsonString);
This is also easier for you to work with. Now that you have this, I'd google something like "javascript get value from property name" for a ton of results.
But basically, there are two ways to get the value of a property:
var xOne = jsonObject.x;
var xTwo = jsonObject['x'];
console.log(xOne);
console.log(xTwo);
This is what you're trying to do:
var varName = 'x';
var myX = jsonObject.varName;
This won't work, because jsonObject doesn't have any field named varName. Instead, you want to access the x field. To do that, you can use bracket [] notation:
var myX = jsonObject['x'];

Javascript - object with key value pair, where value is an array

I'm trying to create an object where there is a key value pair, and the value is an array.
i.e:
foo = {'key1':['val1','val2'], 'key2':['v3','v4']};
Is this possible in pure JS?
e.g.
var foo = {};
foo['key1'] = ['keyOneVal1'];
foo['key1'] = ['keyOneVal2'];
but as you may have guessed, this just overwrites the keyOneVal1.
I've also tried
var foo = {};
foo['key1'].push('k1v1');
foo['key1'].push('k1v2');
but couldn't get it working in a jsfiddle.
EDIT:
Okay heard you guys loud and clear.
This object will not be initialized with an starting key, it's dynamically inserted based on time. So in the end the object will look more like
foo = {'time1':['a','b'], 'time2':['c','d','e','f'], 'time3':['y','y']};
It's very possible. Your second example is the correct way to do it. You're just missing the initializer:
var foo = {};
foo['key1'] = [];
foo['key1'].push('k1v1');
foo['key1'].push('k1v2');
for(var i = 0; i < foo['key1'].length; i++) {
document.write(foo['key1'][i] + '<br />');
}
Try something like this make sure you declare key1:
var foo = {"key1" : []};
foo['key1'].push('k1v1');
foo['key1'].push('k1v2');
It can be done like this
var foo = {"key":[]}
foo["key"].push("val1")
foo["key"].push("val2")

String from jquery array element

I'm looking at arrays in jquery and have this issue, I need to assign a key with a town name, but struggling to understand how to deal with the spaces.
var hashtable = {};
hashtable['Bognor Regis'] = ["lat=50.782998&lng=-0.673061","Sussex"];
var str = hashtable.Bognor Regis[0];
alert(str);
I thought perhaps I could do this
hashtable['Bognor-Regis'] = ["lat=50.782998&lng=-0.673061","Sussex"];
var str = hashtable.Bognor-Regis[0];
then remove the - later, but it only seems to work if i have something like this
hashtable['BognorRegis'] = ["lat=50.782998&lng=-0.673061","Sussex"];
What's the correct way of doing this ?
Thanks
If the keys have spaces you have to use the array accessor to retrieve them:
var hashtable = {};
hashtable['Bognor Regis'] = ["lat=50.782998&lng=-0.673061","Sussex"];
var str = hashtable['Bognor Regis'][0];
alert(str);
Example fiddle

Javascript Split properties into Object exclude inside Strings

What is the best method for splitting or extracting the css properties out of as string and into an object?
var cssProperties = 'background:green;content:"Content;";color:pink;';
The above should result in the following
var theObject = {
background:'green',
content:'"Content;"',
color:'pink'
}
Unfortunately I can not just use a split(";") and cycle through the array due to the semicolon in the url. I could create a giant loop that cycles through every character while skipping the ";" only while wrapped in quotes, but that seems kinda of wrong.
Is there a regex trick for this?
Optional:
Also are there any really good regex websites. I understand most of the syntax but there doesn't seem to be many practical really complicated examples on most of the websites I have found.
Here is a fiddle further demonstrating the function: http://jsfiddle.net/ZcEUL/
(function() {
var div = document.createElement('div'),
rprops =/[\w-]+(?=:)/g,
rcamelCase = /-(\D)/g,
fcamelCase = function(a,letter) {
return letter.toUpperCase();
};
window['styleToObject'] = function(str) {
var props = str.match(rprops),
prop, i = 0,
theObject = {};
div.style.cssText = str;
while (prop = props[i++]) {
var style=div.style[prop.replace(rcamelCase,fcamelCase)];
if (style) {
theObject[prop] = style;
}
}
return theObject;
};
})();
Here was the solution I made regarding your first css string you had listed... Not the best but maybe it'll help spark some ideas.
JSFiddle Example
Try this or something similar
var newString = cssProperties
.replace(":", ":'")
.replace(";", ", '");
var obj = eval(newString);

Categories