check for undefined not working - javascript

I just started programming with javascript no long ago. But I am still confused with the way it handles arrays.
the problem is that I have an array in which there some content as undefined. I want to check for those undefined values and escape them. How do I do it. the following code is not working and I have not found a way to solve this problem.
if(myarray[0]!=='undefined')
if(myarray[0])!='undefined') // I have also tried
if(myarray[0]).search('undefined')==(-1)) // and also this
however none of these options is working. I could see when debugging that the value in the array is 'undefined' but the condition is never met. once again my aim is to do something when it is not undefined. please how could I do it. I found a similar question Test if something is not undefined in JavaScript but it does not work

You are comparing undefined to 'undefined', which is a string so its different. You need to compare like this:
myarray=[undefined];
if(myarray[0]!==undefined){
console.log(4)
}

juvian provided a good answer. You need to use undefined instead of 'undefined' because you are comparing your array to a string.
On my current project, I use underscore to check for undefined. It's pretty simple and straight-forward.
var array = [];
if (_.isUndefined(array));
http://underscorejs.org/#isUndefined

You're comparing the myarray[0] value to a string value of undefined.
What you need is this:
if (typeof(myarray[0]) !== 'undefined')
Hope this helps!

You should check it as follows: if(typeof(myarray[0]) != 'undefined')

Related

Using a for loop in JavaScript to loop over an array of objects

My code and terminal
Just ignore the comments, they are in danish as it is for a school assignment..
I need some help. My loop keeps giving me an undefined value in my terminal, and I can't seem to find the issue. It is working as it should, and gives me the correct values, but still has those 'undefined' ones which irritates me.
EDIT: Has been fixed by #aqq, thx for the help everybody!
As #dikuw mentioned the undefined call might be coming from the gørBeskedPersonlig function being called.
I don't see that function being defined in your code so that's probably it, try commenting out the following line:
console.log(gørBeskedPersonlig(katalog[index].navn));
UPDATE: After reviewing your code, i can see that the function gørBeskedPersonlig was not returning anything.
Updating it to return the new value has fixed the "undefined" error.
function gørBeskedPersonlig(navn){
hemmeligBesked.splice(1,1,navn+'!');
return hemmeligBesked.join(' ');
}
It seems that you have some console.log() in function gørBeskedPersonlig that is returning undefined. Send a code for that function.

How to remove 'Undefined' status on forEach function variable

Im a beginner to coding JS. When im trying to create an array function for diplaying object reference. I write it on the VS code. See the image for the details.
The problem is that i want to remove the 'undefined' status that is printed on the cmder. Im using Node and cmder to run the code.
Hope this clear for you to understand my problem. Thanks
You are logging the return value of foodList.
foodList returns the return value of forEach.
forEach always returns undefined
If you don't want to log that, then remove the console.log() from around the return value of foodList.
You are doing
console.log(foodList(animal))
this console.log is returning undefined
do this
foodList(animal)
Yes, it's my fault, i didnt know that console.log return undefined when using forEach(). Sorry everyone, my bad. Thanks for the helps!

How to use a multi-variable string in the name of a variable in pure js

I'm a huge JS nub and still getting used to the syntactical nuances. Essentially, I'm looking to reduce the following to a single line:
if (player==1) {variable1[arrayposition] = thisvalue;}
if (player==2) {variable2[arrayposition] = thisvalue;}
You can use a ternary operator to define the "variable" to use and, assuming the array position and value are the same use it all on one line:
(player === 1 ? variable1 : variable2)[arrayposition] = thisvalue;
I am assuming player can only be equal to 1 or 2. If you have to, you should null check or check for other values, you should do this elsewhere or additionally.
If you really have to, then:
[variable1, variable2][player-1][arrayposition] = thisvalue;
//this is a one-liner. Short but hard to read.
Demo: http://jsfiddle.net/DerekL/c3Lxn/
However the way you are doing it right now is okay. There is nothing wrong with it.
Try this, using a map, this support numbers and strings
({
"1" : variable1,
"2" : variable2,
})[player+''][arrayPosition] = thisValue
Thanks for both those answers! I learned useful things I didn't know. What I was really hoping was I could have an array within an array (but I couldn't get this syntax to fly):
variable[playernumber][arrayposition] = thisvalue;
Is it possible I'm approaching the problem inefficiently and should instead be thinking of "variable" as an object which contains an array?

Javascript json, check all keys for undefined ('null') and set default

Firstoff I'd like to add I've been learning javascript for like only 2 days now. I'm pretty much way ahead of myself with what I'm trying to get but here goes.
I have a json array from which I get data to replace/insert in my page. The first problem I have is that if it comes across an empty ('null') key it will just stop. Will not even try to continu.
document.getElementById("id1")src=json.img1.link;
document.getElementById("id2")src=json.img2.link;
document.getElementById("id3")src=json.img3.link;
json.img2.link is empty ('null' response from json.). javascript will then not replace "id2" but it also won't replace "id3".
I'm now trying to find a solution where it will if nothing else at least set a default.
The script is not continuing executing because it comes to an error --trying to access property link of an undefined object
Try
document.getElementById('id2').src = json.img2 ? json.img2.link : 'defaultLink';
This way your are checking for undefined (ie null) object in img2 and assigning the default value. This assumes that what is not defined (null) is the img2 object.
Actually I don't think your code should work at all, you are missing the. before the src So, try
document.getElementById("id1").src=json.img1.link;
document.getElementById("id2").src=json.img2.link;
document.getElementById("id3").src=json.img3.link;
and let us know if that doesn't solve the problem.
Btw, +points for learning JavaScript and not just straight into jQuery!

Why is 'indexOf' not returning anything?

The book I am reading tells me to open up the JavaScript console and try the code "foo: bar".indexOf(":"). I've tried it in many ways. I tried removing quotation marks, putting it inside a show() and alert() function. I just can't seem to tease anything out.
Has something changed in JavaScript? Has the author made a mistake? Am I supposed to get no return? Do I need to append document.write, perhaps? Any help greatly appreciated.
Yes something changed in Firefox 5+
However the console (ctrl-shift-k) still works
In the error console (ctrl-shift-J) you will need to wrap it in alert:
foo:bar is a property definition in json, and indexOf is supposed to deal with a left value (string variable, constant, or at least something that can have characters in it. I don't know why the book you are reading wants you to do this, but it doesn't seem to be correct. The correct way to use indexOf would be :
var myObject = {
foo:"bar"
}
alert(myObject.foo.indexOf("a"));
try like follows, it should work. Generally the indexOf() will return -1 if the value to search for never occurs.
var str="foo:bar";
document.write(str.indexOf(":") + "<br />");
The output should be 3

Categories

Resources