1) Why in IE 8 typeof(window["alert"]) is "object" and not function?
2) How I can call apply method on "window.alert" ? I mean that what i'm trying to do is this:
function exec(method, param)
{
//because of typeof(window["alert"]) == "object" the actual if looks like typeof(window[method]) == 'function' || method == 'alert'
if(typeof(window[method]) == 'function')
{
window[method].apply(window, [param]);
}
}
exec("alert","hello");
typeof window['alert'] is a "function"... (tested with FF)
try this code (typeof instead typeOf())
function exec(method, param)
{
if(typeof window[method] == 'function')
{
window[method].apply(window, [param]);
}
}
exec("alert","hello");
typeof window["alert"] returns "object" in Internet Explorer versions below 9, but in Firefox it returns "function" . It's a known issue I guess. Below, here's an article that mentions it :
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/typeof?redirectlocale=en-US&redirectslug=Core_JavaScript_1.5_Reference%2FOperators%2FSpecial_Operators%2Ftypeof_Operator
typeof(window["alert"]) returns "function"
you have written typeOf. This works
function exec(method, param)
{
//because of typeof(window["alert"]) == "object" the actual if looks like typeof(window[method]) == 'function' || method == 'alert'
if(typeof(window[method]) == 'function')
{
window[method].apply(window, [param]);
}
}
exec("alert","hello");
Related
For example, in iOS Swift, I can do something like this:
if (self.user?.company?.pic?.phoneNumber != null) { doSomething() }
Without the need to:
if (self.user != null && self.user!.company != null && self.user!.company!.pic != null && self.user!.company!.pic!.phoneNumber != null) { doSomething() }
In ReactNative (or Javascript), I found out that if an object is undefined, I can't check for the existence of the variable inside of it, so I have to check first whether the object is undefined or not, only then I can safely check whether the variable inside of it undefined or not.
if (typeof this.state.user !== "undefined" && typeof this.state.user.company !== "undefined" && typeof this.state.user.company.pic !== "undefined" && typeof this.state.user.company.pic.phoneNumber !== undefined) { this.doSomething() }
How can I turn this into just:
if (typeof this.state.user.company.pic.phoneNumber !== "undefined") { this.doSomething() }
or something similar?
Thanks.
Currently, optional chaining is a stage 3 draft, and so, you may be able to do it in the future.
EDIT:
Optional chaining will now be part of ES2020, and so you'll be able to do the following:
if (self.user?.company?.pic?.phoneNumber !== undefined) {
doSomething(); // phoneNumber exists
}
With that being said, it still has very limited browser support.
So, for the time being, you could instead create a function which recursively finds each object from a list of properties like so:
const optional_chain = (obj, [key, ...props]) =>
obj !== undefined && key ? optional_chain(obj[key], props) : obj;
const user = {
company: {
pic: {
phoneNumber: 1
}
}
}
console.log(optional_chain(user, ['company', 'pic', 'phoneNumber'])); // 1
console.log(optional_chain(user, ['company', 'pic', 'phoneNumber', 'x'])); // undefined
console.log(optional_chain(user, ['company', 'picture', 'phoneNumber'])); // undefined
console.log(optional_chain(user, ['x', 'picture', 'phoneNumber'])); // undefined
In your case, the usage would be as so:
if (optional_chain(self.user, ['company', 'pic', 'phoneNumber']) !== undefined) {
doSomething();
}
If you can’t use optional chaining which is still a proposal but available via babel plugin you could use a recursive utility function to test for the presence of each path segment:
const pluck = (item, path) => {
const [, part, rest] = /^([^.]+)\.*(.*)/.exec(path) || [];
if (!part) {
return null;
}
const o = (item || {})[part];
if (o == null) {
return null;
}
return rest.length ? pluck(o, rest) : o;
};
if (pluck(this.state, ‘user.company.pic.phoneNumber’)) {
doSomething();
}
I cant seem to figure this answer out so maybe you could help shed some light. In my defense, undefined is a message returned when a variable, key, value etc could not be found. A message should be a string? No?
let foo = [{id: 1, you: "me"}]
let undif = foo.find(i => i.he === 1)
if (typeof undif === "undefined") {
console.log(undif) // not fired
}
if (typeof undif == undefined) {
console.log(undif) // not fired
}
if (typeof undif == 'undefined') {
console.log(undif) // fired!
}
Why cant I use typeof undif === 'undefined?
triple equals looks for both value and type;
hence undefined === 'undefined' will return false
for same reason your first case returns true
This is a wonderful article on double equals and triple equals along with falsy value comparsion
Your code had syntax errors (missing the opening braces after every if), but once those are fixed, the first and third are both fired.
let foo = [{id: 1, you: "me"}]
let undif = foo.find(i => i.he === 1)
if (typeof undif === "undefined") {
console.log('1', undif) // fired
}
if (typeof undif == undefined) {
console.log('2', undif) // not fired
}
if (typeof undif == 'undefined') {
console.log('3', undif) // fired!
}
function $(e){return document.querySelector(e)}
I use this as a shorthand for querySelector.
For example: $('.MainClass').style.display='none';
It actually works too, but Chromes Console logger shows an error:
Uncaught SyntaxError: Failed to execute 'querySelector' on 'Document': '[object HTMLDocument]' is not a valid selector.
Which is weird, because when using $('cssslectorhere') it still works. The reason I did this because I was so used to jQuery, that I liked the $ symbol. But I hate seeing that error in the console log, anyway to remove it?
You have not provided all of the code. Somewhere, you're doing this:
$(document)
This works in jQuery, but it will not work with querySelector because it isn't a selector.
Either remove that usage, or change your $ function to handle document.
function $(e){
return e === document ? document : document.querySelector(e);
}
It sounds like your code is somewhere trying to pass the document object instead of a string selector as in $(document). You could work around that by changing your code to this:
function $(e){
if (typeof e === "string") {
return document.querySelector(e);
} else {
return e;
}
}
Then, this would work with any DOM object that you passed such as document or document.body.
Or, you could make it a quite a bit more foolproof:
//Returns true if it is a DOM node
function isNode(o){
return (
typeof Node === "object" ? o instanceof Node :
o && typeof o === "object" && typeof o.nodeType === "number" && typeof o.nodeName==="string"
);
}
function $(e) {
if (typeof e === "string") {
return document.querySelector(e);
} else if isNode(e) {
return e;
} else {
throw new Error("arg in $(arg) must be selector string or DOM node");
}
}
See this prior answer for a discussion/reference for the isNode() function.
This question already has answers here:
JavaScript isset() equivalent
(28 answers)
Closed 6 years ago.
How to check isset in javascript.
I have used in the following way.
var sessionvalue = document.getElementById('sessionvalue').value;
if(Here I have to check if isset the sessionvalue or not){
if(sessionvalue == "" || sessionvalue == null)
{
document.getElementById('sessionvalue').style.borderColor="red";
return false;
}
else
{
document.getElementById('sessionvalue').style.borderColor="#ccc";
}
}
When javascript variables are not declared and you try to call them, they return undefined, so you can do:
if (typeof sessionvalue == "undefined" || sessionvalue == null)
You can just do:
if(sessionvalue)
The above will automatically check for undefined, null (And NaN ,false,"")
You can even make it a global function if you need it like you're used to in php.
function isset(_var){
return !!_var; // converting to boolean.
}
if(typeof(data.length) != 'undefined')
{
// do something
}
if(empty(data))
{
// do something
}
if(typeof(data) == 'undefined' || data === null)
{
//do something
}
you can just do if(sessionvalue) that's it you don't need anything else and remember you can compare apples with cars in javascript, you can check if value is null or undefined with if(sessionvalue) or if(!sessionvalue), your code will be :
document.getElementById('sessionvalue').style.borderColor= sessionvalue ? "red" : "#CCC";
Try Code as below
var sessionvalue=document.getElementById('sessionvalue').value;
if(typeof sessionvalue != 'undefined'){
if(sessionvalue=="" || sessionvalue == null)
{
document.getElementById('sessionvalue').style.borderColor="red";
return false;
}
else
{
document.getElementById('sessionvalue').style.borderColor="#ccc";
}
}
If I run this code on IE8 or lower, I get this error: Object doesn't support this property or method
var hasFlash = ((typeof navigator.plugins != "undefined" && typeof navigator.plugins["Shockwave Flash"] == "object") || (window.ActiveXObject && (new ActiveXObject("ShockwaveFlash.ShockwaveFlash")) != false));
Maybe the new ActiveXObject part is failing, because ActiveXObject is (in your current setup) not anything that the new operator can be applied to -- or 'ShockwaveFlash.ShockwaveFlash' isn't a valid input and therefore an exception is thrown.
You can however easily rewrite your code to address that problem:
var hasFlash = (function() {
if (typeof navigator.plugins != "undefined" && typeof navigator.plugins["Shockwave Flash"] == "object") {
return true;
} else if (typeof window.ActiveXObject != "undefined") {
try {
new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
return true;
} catch (e) { }
}
return false;
})();