Archive for the ‘javascript’ Category
cssRules null in Chrome
I found this problem when tryed to use cssRules of document.styleSheets[i] locally in Chrome but found that cssRules is null and only in Chrome. I need only to add some rules but not to read or modify existed rules so this fix is not for all.
Here’s the bug http://code.google.com/p/chromium/issues/detail?id=49001.
And here’s my workaround for this problem:
var styles = document.styleSheets; var style = null; for (var s = 0; s < styles.length; s++) if(!styles[s].href) { style = styles[s]; break; } if (style == null) style = jQuery("<style type=\"text/css\"></style>") .appendTo('head').get(0); var rules = style.cssRules; // is not null!!!
Accessing a dimensional array in JavaScript
Let’s declare a two dimensional array and try to access the element. Here is the first example:
var array = [[1, 2, 3],[4, 5, 6]]; alert(array[1][1]); // Output: 5
Here is the same sample but with another sytnax:
var array = new Array(2); array[0] = new Array(3); array[0][0] = 1; array[0][1] = 2; array[0][2] = 3; array[1] = new Array(3); array[1][0] = 4; array[1][1] = 5; array[1][2] = 6; alert(array[1][1]); // Output: 5
Again, another syntax of this example to access a javascript array:
var array = new Array(new Array(1, 2, 3), new Array(4, 5, 6)); alert(array[1][1]); // Output: 5
Some developers make the following error when accessing a JavaScript array and wait that the 5 will be returned:
var array = [[1, 2, 3],[4, 5, 6]]; alert(array[1,1]); // Output: [4, 5, 6]
JavaScript interpretes 1,1 as a comma separated expression and this expression returnes 1. Each part of the comma separated expression is executed left to right. The final value of the comma separated expression is the value of the last comma part. So, when you try to evaluate the following script in the sample below you will get the last array item because the value of the comma separated expression 0,1,2 will be 2:
var array = [1, 2, 3]; alert(array[0,1,2]); // Output: 3
How to test for an empty javascript object
Hi everybody! I’ve just had a discussion of how to test for an emtpy javascript object. As a result, I have several code snippets and I want to share them with You.
Problem
alert({}==null); // false alert({}=={}); // false alert({}=={}); // false alert({}==0); // false alert({}==""); // false alert({}==[]); // false // etc :)
So, none of the expressions above can check for an empty javascript object.