I have a javascript object like this
var obj={
a:{x: "someValue", y:"anotherValue"},
b:{x: "bValue", y:"anotherbValue"}
};
and I am trying to reference it like this
function(some_value){
alert("some_value is " + some_value + " with type " + typeof some_value);
// prints some_value is a with type string
var t;
t=obj[some_value]["x"]; // doesn't work
some_value="a";
t=obj[some_value]["x"]; // this does work
t=obj["a"]["x"]; // and so does this
}
I would really like understand what is going on here . Ideally I'd like to reference my
object with the value passed to the function.
Thanks
I can only assume that your variable some_value must not contain the value a. It is possible that it has extra white space characters.
In JS, when a property does not exist, it returns an undefined. in the case of the following code, if the value contained in the variable some_value does not exist as a property in obj, t is undefined
//if some_value is neither a nor b
t = obj[some_value] // t === undefined
if you try to extract a property from an undefined value, the browser reports an error:
//if some_value is neither a nor b
t = obj[some_value]["x"] // error
you can check the existence of a property before you try accessing it by using hasOwnProperty().
if(obj.hasOwnProperty(somevalue)){
//exists
} else {
//does not exist
}
you can do a "loose check" but it's not reliable as anything "falsy" will call it "non-existent" even though there is a value.
if(obj[somevalue]){
//is truthy
} else {
//obj[somevalue] either:
//does not exist
//an empty string
//a boolean false
//null
//anything "falsy"
}
Related
I'm trying to construct the variable name and then test if it exists using a while loop but I think I'm creating it when I test for it so keep getting 'true' and the loop goes infinite.
var1 = "value1"
var2 = "value2"
var3 = "value3"
var i = 3
Logger.log(('value'+i)==true)
var i = 4
Logger.log(('value'+i)==true)
/*
var i = 1;
while (("value"+i) != null) {
Logger.log("value"+i)
i++;
}
*/
When I build the loop I want value4 to not exist and stop the loop but it doesn't. Because I've just created it's string I suppose, so how should I be formatting the test? First question here and I have searched but the 'construction' part seems to complicate things. Thanks.
Firstly, I'll clarify a misconception,
I want value4 to not exist and stop the loop but it doesn't. Because I've just created it's string I suppose
'value'+i doesn't create a variable. It represents the string 'value3'. In JS, strings are truthy, so you logger will print true.
Now to the question, how to check if variable exists.
The cleanest way of doing this would be to use a dictionary represented by a simple js object.
let definedVariablesDictionary = {};
definedVariablesDictionary.var1 = 'value1';
let isVarialbeDefined = variable => definedVariablesDictionary[variable] !== undefined;
console.log(isVarialbeDefined('var1')); // true
console.log(isVarialbeDefined('var2')); // false
Variable names are not strings, so your attempt to construct a string that matches the name of a variable won't evaluate that string as code.
If you want to do this, you should create an object with properties that store values, like a variable would. Then you can pass a string of the property name into the object, to retrieve the value of the property.
Also, you shouldn't check to see if the value is null as null is a valid value that a variable or property could have been set to. That check wouldn't tell you explicitly if the property was defined or not, it would only tell you if the value of the property was null. Instead, checking for the existence of the property can be done by just passing the property name into the object. If it exists, then the result is "truthy" and your if statement would proceed into the true branch. If the property doesn't exist, the return value is falsy and you'd proceed into the false branch.
let myObject = {
value1:"test1",
value2:"test2",
value3:"test3"
};
for(var i = 0; i < Object.keys(myObject).length +1; i++){
// Property names can be passed as strings using bracket notation
if(myObject["value" + i]){
console.log("value" + i + " exists and has a value of: " + myObject["value" + i]);
} else {
console.log("value" + i + " is not defined");
}
}
I would like to be able to define an object that will evaluate to a primitive but also may have attached functions. Effectively the same way the "String" class works. Is there a way for me to extend the class without modifying the String prototype.
One use case for me would be like this:
class ID extends String{
constructor(len){
let value = 'Very unique id';
this.len = len;
this = value; //Or some other way of assigning the objects value
}
someRandomFunction(){
console.log('I was called');
}
}
const newId = new ID(10);
console.log(newId) // prints "Very unique id"
newId.someRandomFunction() // prints "I was called"
console.log(newId.len) // prints "10"
Most situations where this will be relevant, you will be implicitly calling newId[Symbol.toPrimitive](). You can define this function on your object, which will result in being able to precisely define how your object behaves when you attempt to use it as different things.
In your case, it's a wrapper object around a string value, right? You could simply return the string for all calls to toPrimitive, and thus any attempt to use your object as anything other than an object will result in the operation being performed on the backing string instead. Here's an example:
class ID {
constructor(len){
this.value = 'Very unique id';
this.len = len;
}
[Symbol.toPrimitive](hint){
return this.value;
}
someRandomFunction(){
console.log('I was called');
}
}
const newId = new ID(10);
console.log('' + newId) // prints "Very unique id"
newId.someRandomFunction() // prints "I was called"
console.log(newId.len) // prints "10"
Note that console.log is a bit of a finicky function: it checks the type of the argument (which you cannot change) and if it's an object, it won't coerce it to anything but run some code to inspect the object's properties. So console.log(newId) you'll never get to have a satisfying custom output (unless you're in node.js). It will always print like an object. However, any attempt to coerce the object to a primitive, as in '' + newId will result in your desired behavior.
code have to do 3 things
get json output of user.
get user status on-line or off-line (if data.stream === null) user is off-line
create user with nickname and status.
push that user into array. lastData array
1st problem i get TypeError data.sream is null even if i define null as in examples. some people say`ed that i can just ignore that, but i want to ask professionals
-- Pritam Banerjee answer this question thank you
2nd problem is that user is not pushed into array. only same user is pushed few times in array.
Code is here Fiddle
sorry if question is not good but i dont know where else to ask.
var mynull = null;
if (typeof mynull === null) { // have to be if(mynull == null)
// my code
}
else
//my code
// building prototype name & status
function userStatus(name, status) {
this.name = name;
this.status = status;
} // prototype
var showUserList = ["OgamingSC2", "habathcx", "RobotCaleb", "noobs2ninjas"]
var lastData = []; // where to push users
for (var i = 0; i < showUserList.length; i++) {
var user = showUserList[i]; // get username from array
var useris = showUserList[i] // --//--
useris = new userStatus(user, 'Chanel is Offline');
lastData.push(useris);
console.log(lastData[i].name + '' + lastData[i].status);
}
Some things you must know about the typeof operator:
It always returns a string. Never compare the returned value to a non-string using ===.
It's horribly broken because it doesn't always not return the Type of the value.
For example, typeof null returns the string 'object'.
The proper way to compare mynull with null is mynull === null.
You can also use mynull == null to detect if it's either null or undefined.
null is an important primitive type in JavaScript. It is essentially a special value that indicates that there is no value! Initializing your variables to null when you don't know yet what their actual value will be later on is a very good best-practice in JavaScript, because if you wind up getting an error (like the one you are getting now (TypeError data.sream is null), it tells you that you never actually supplied a useful value to the variable.
When it comes to testing for null, you have a few options, but something that is important to remember is that JavaScript is loosely typed and values can and do change their type simply based on the way you use them. null is what's known as a "falsey" value, that is, if you convert it to a Boolean, it converts to false. Other "Falsey" values include: 0, undefined, "" and false. Just about every non-empty, non-zero, non-undefined value is "truthy" and will convert to true if forced into a Boolean.
So, if you really just want to know if your variable is still null or does it have meaningful data, you can leverage this loose typing like the following because the value of myNull will be converted to a Boolean so that the if statement can be evaluated.
Ask yourself if you really care if your variable has the exact value of null or do you just need to know if your variable has data that you can use? An explicit test for null may not really even be needed.
var myNull = null;
var myNull2 = null;
// We're only going to give one of the variables a value
myNull2 = "something";
if(myNull){
// myNull is NOT null
console.log("myNull is NOT null and has a value of: " + myNull);
} else {
// myNull is null
console.log("myNull IS null and has a value of: " + myNull);
}
if(myNull2){
// myNull2 is NOT null
console.log("myNull2 is NOT null and has a value of: " + myNull2);
} else {
// myNul2l is null
console.log("myNul2l IS null and has a value of: " + myNull2);
}
This will not work as:
typeof null === 'object';
So it will always return an object and hence your code will not work.
Rather you can try:
if (myNull == null){
// your code here.
}
Also can try as suggested by Scott, but the if else would be the other way round:
if (myNull){}
Sometimes I see that it is common to do this on javascript in order to check if a variable is not undefined because it has a value assigned:
if(variable) {
/* not undefined, do something */
}
However, I was asking to myself how can I check if variable is not undefined in the following situation:
Live Demo: http://jsfiddle.net/Vp8tN/1/
$(function() {
var person = create('John');
var isMarried = person.isMarried;
console.log('isMarried: ' + isMarried);
if(isMarried) {
console.log('Do something!');
}
});
function create(name) {
var person = {};
person.name = name;
person.isMarried = getRandom();
return person;
};
function getRandom() {
var arr = [true, 'No', undefined];
var rand = arr[Math.floor(Math.random() * arr.length)];
return rand;
};
In this case isMarried variable can be true, 'No', or undefined.
So, my questions are...
1) How can I check if isMarried variable is NOT undefined because it is === true (equals true) or because it has a value assigned? (this last one happens when isMarried === 'No').
2) Is it possible to check this without using an extra if statement or condition?
3) What's the better approach for checking this?
In both cases described above (at number 1) I got inside the if statement. Check the output from browser console:
isMarried: true
Do something!
isMarried: undefined
isMarried: No
Do something!
PS. I am using jQuery just for testing, this question is NOT related to that framework! Thanks.
You have three options for a single equality test:
Strict Equality. if (person.isMarried === true) or if (person.isMarried !== undefined). Check if a variable is explicitly equal to something (with no type conversions allowed).
Loose equality. if (person.isMarried == true) with type conversions allowed.
Any truthy/falsey value. if (person.isMarried). This will be satified if person.isMarried contains ANY truthy value. Even "no" would be a truthy value.
If you're trying to tell the difference between "no", false and undefined, you will likely have to use more than one comparison as those are all separate values of separate types.
If you only want to know if the variable has any value (e.g. is not undefined), then you can use the strict equality check and compare to the actual undefined value:
if (person.isMarried !== undefined) {
// there is some value in person.isMarried though it could be anything
// other than the undefined value
}
isMarried !== undefined
Yes, see #1.
1
See this post.
https://stackoverflow.com/a/3390426/1313439
EDIT: For reasons that jfriend00 pointed out in the comments to his answer, isMarried !== undefined is probably preferable to typeof isMarried !== 'undefined'.
I want to test whether a JavaScript variable has a value.
var splitarr = mystring.split( " " );
aparam = splitarr [0]
anotherparam = splitarr [1]
//.... etc
However the string might not have enough entries so later I want to test it.
if ( anotherparm /* contains a value */ )
How do I do this?
if (typeof anotherparm == "undefined")
An empty string evaluates to FALSE in JavaScript so you can just do:
if (anotherparam) {...}
In general it's sort of a gray area... what do you mean by "has a value"? The values null and undefined are legitimate values you can assign to a variable...
The String function split() always returns an array so use the length property of the result to figure out which indices are present. Indices out of range will have the value undefined.
But technically (outside the context of String.split()) you could do this:
js>z = ['a','b','c',undefined,null,1,2,3]
a,b,c,,,1,2,3
js>typeof z[3]
undefined
js>z[3] === undefined
true
js>z[3] === null
false
js>typeof z[4]
object
js>z[4] === undefined
false
js>z[4] === null
true
you can check the number of charactors in a string by:
var string_length = anotherparm.length;
One trick is to use the or operator to define a value if the variable does not exist. Don't use this if you're looking for boolean "true" or "false"
var splitarr = mystring.split( " " );
aparam = splitarr [0]||''
anotherparam = splitarr [1]||''
This prevents throwing an error if the variable doesn't exist and allows you to set it to a default value, or whatever you choose.
So many answers above, and you would know how to check for value of variable so I won't repeat it.
But, the logic that you are trying to write, may be better written with different approach, i.e. by rather looking at the length of the split array than assigning to a variable the array's content and then checking.
i.e. if(splitarr.length < 2) then obviously anotherparam is surely 'not containing value'.
So, instead of doing,
if(anotherparam /* contains a value */ )
{
//dostuff
}
you can do,
if(splitarr.length >= 2)
{
//dostuff
}