I have a small script that looks like this:
hideElements = arguments.shift().split ( ',' );
for ( iterator in hideElements ) {
console.log (' --> hiding ' + hideElements[iterator] );
lg_transitions ( {kind:"slide-up"} , { target : hideElements[iterator] } );
}
When I run it in the debugger all things start quite rationally. I put a breakpoint at the first line listed above. After pressing the "step over next function call" button to initialise the "hideElements" variable to the following:
This is what is what I would have expected but then after completing the first (and should be the only) iteration it comes back to the head of the loop and the "iterator" which had started at 0 has now strangely changed to "remove". Huh? No idea where that came from. But in the console.log message that follows there might be a hint ... it prints the following to the console:
This is a function called -- you guessed it -- "remove". It is a function that I added recently for a different reason but it is not called directly or indirectly and so I'm at a loss as to why this would be picked up here. For anyone interested in the full code for "remove", here it is:
// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
}
ADDITION:
The code I had neglected to add earlier was the initialisation of the arguments array. Here's what I had (note I've since changed the name to "args" instead of arguments):
function ConditionalFormatting ( key , eventObject , setOfRules ) {
console.log ("Entering conditional formatting: key is " + key + ", eventObject is " + eventObject.attr('id') + ", setOfRules is " + setOfRules );
var ruleStrings = [];
ruleStrings = setOfRules.split (';');
var targetOverride = false;
jQuery.each ( ruleStrings , function ( i , ruleString ) {
// There is a rule, now let's find out which one
var targetElement;
var args = [];
args = ruleString.split('::');
var rule = args.shift();
#Yoshi is right: for in will list all fields in the object - which is what the array actually is.
Try using the hasOwnProperty method:
hideElements = arguments.shift().split ( ',' );
for (iterator in hideElements ) {
if (hideElements.hasOwnProperty(iterator))
{
console.log (' --> hiding ' + hideElements[iterator] );
lg_transitions ( {kind:"slide-up"} , { target : hideElements[iterator] } );
}
}
This is why you should usually avoid using for in to iterate over arrays and use a normal for loop instead. jsHint/jsLint will give you a message like this for the code you posted:
The body of a for in should be wrapped in an if statement to filter unwanted properties from the prototype.
Sidenote:
for (iterator in hideElements ) will create a global variable iterator, while for (var iterator in hideElements ) won't.
The arguments object is not an actual array. Therefore it doesn't have the shift() function. If you want the first object in the array, obtain the element at index 0 (first object). Moreover, use a regular for loop to traverse the arguments object.
hideElements = arguments[0].split(',');
for ( var i = 0; i < hideElements.length; i++ ) {
...
}
arguments is not a real array, however, if you wish to use it like it were an array, then use Array.prototype.slice.call( arguments );:
if ( arguments.length > 0)
hideElements = Array.prototype.slice.call( arguments ).shift();
From there on you can use hideElements as an array.
Related
I'm going through a Javascript course and its challenges. I don't have a question about how to do this particular challenge but I was going through the code in my mind to make sure I understood all of it and I ran into a question.
var strength = true;
var fear = false;
var pack = {
foodPouch: ['carrot', 'mystery meat', 'apple', 42],
addFood: function(foodItem) {
this.foodPouch = this.foodPouch || [];
this.foodPouch.push(foodItem);
},
gobbleFood: function(foodItem) {
return(this.foodPouch.indexOf(foodItem) >= 0) ?
this.foodPouch.splice(this.foodPouch.indexOf(foodItem), 1)[0] :
alert('Your pack lacks ' + foodItem);
},
feedBird: function(birdFood) {
for (var i = 0; i < this.foodPouch.length; i++) {
if (this.foodPouch[i] == birdFood) {
alert('Feed beggar bird ' + this.foodPouch[i]);
}
}
}
};
pack.feedBird('42');
My question is with this line:
return(this.foodPouch.indexOf(foodItem) >= 0) ?
this.foodPouch.splice(this.foodPouch.indexOf(foodItem), 1)[0] :
alert('Your pack lacks ' + foodItem);
Why does the first ternary action that splices the array end with [0], which I believe makes that whole action into the value of the spliced array? I can see if you wanted to declare it as some kind of variable, but it seems like the main purpose is just to splice it off. Does it matter if that [0] is there at all?
splice removes elements from an array, then returns an array containing the removed elements.
In this case, the gobbleFood function is checking for the presence of a particular item (using indexOf) and is removing and returning the first instance of it if it exists in foodPouch.
The removal is done using splice, and since splice returns an array of items removed, even if it's only removed 1 item as in this case, it's necessary to use [0] as an indexer to get at the single item that was removed.
return(this.foodPouch.indexOf(foodItem) >= 0) ?
this.foodPouch.splice(this.foodPouch.indexOf(foodItem), 1)[0] :
alert('Your pack lacks ' + foodItem);
This statement translated to English says:
Return "the zeroth element of the 'returned array' after removing the foodItem" if it exists there. Or just display a message if it is not.
Or I can write it in this manner in JS:
if (this.foodPouch.indexOf(foodItem) >= 0) {
var removedItems = this.foodPouch.splice(this.foodPouch.indexOf(foodItem), 1);
return removedItems[0];
};
else
alert('Your pack lacks ' + foodItem);
I need a little help here. I want a script that converts all the AI files in all the subfolders into PDFs and puts them in a single folder at the root and I want it to skip any folders named "Resources". I found a script that mostly does what I need it to do and I have modified it further to suit our exact needs. I'm struggling with 2 parts of it though. Specifically lines 33 and 80 are my issues now.
#target illustrator
main();
//
function main() {
var topLevel = Folder.selectDialog( 'Select the top level folder to start converting AI files to PDFX files' );
var proofFolder = new Folder( topLevel + '/Proofs2/');
proofFolder.create();
if ( topLevel != null ) {
processDocs( recursiveFolders( topLevel, /\.ai$/i ), getPDFOptions() );
};
};
//
function processDocs( aiFiles, opts ) {
var i, baseName, doc, saveFile;
for ( i = 0; i < aiFiles.length; i++ ) {
doc = app.open( aiFiles[i] );
baseName = decodeURI( doc.name.match( /(.*)\.[^\.]+$/ )[1] );
//This is line 33// saveFile = File( proofFolder.path + baseName + '.pdf' );
doc.saveAs( saveFile, opts );
doc.close( SaveOptions.DONOTSAVECHANGES );
};
};
//
function getPDFOptions() {
var pdfSaveOpts = new PDFSaveOptions();
pdfSaveOpts.acrobatLayers = true;
pdfSaveOpts.colorBars = false;
pdfSaveOpts.colorCompression = CompressionQuality.AUTOMATICJPEGHIGH;
pdfSaveOpts.compressArt = true;
pdfSaveOpts.embedICCProfile = true;
pdfSaveOpts.enablePlainText = true;
pdfSaveOpts.generateThumbnails = true;
pdfSaveOpts.optimization = true;
pdfSaveOpts.pageInformation = true;
pdfSaveOpts.preserveEditability = true;
pdfSaveOpts.pDFXStandard = PDFXStandard.PDFX1A2001;
pdfSaveOpts.viewAfterSaving = false;
return pdfSaveOpts;
};
//
function recursiveFolders( fold, exp ) {
var fileList = Array(); // Our matching files…
getFiles( fold, exp, fileList );
return fileList;
};
//
function getFiles( fold, exp, array ) {
//This is line 80// if (Folder.name !== /\Resources$/){
var i, temp;
temp = Folder( fold ).getFiles(); // All files and folders…
for ( i = 0; i < temp.length; i++ ) {
if ( temp[i] instanceof File && RegExp( exp ).test( temp[i].fsName ) ){
array.push( temp[i] );
};
if ( temp[i] instanceof Folder ) {
getFiles( temp[i].fsName, exp, array );
};
};
return array;
};
};
Line 33:
Variables in Javascript are local to the function they are defined in. That is, if you try
a();
function a()
{
var a1 = 1;
b();
}
function b()
{
alert ("var a1 = "+a1);
}
you will find a1 is undefined inside function b. Two common solutions (there may be more) are to put the variable in the function definition:
b(a1);
..
function b (myVarArg)
{
alert ("var a1 = "+myVarArg);
}
or -- simple but slightly error-prone -- declare the variable at the very top of your program before main:
var a1;
This is a quick and simple solution; the variable will be 'visible' inside all functions, and assigning a new value anywhere will work. It is 'slightly error-prone' because a local variable with the same name (defined inside a function) will effectively 'hide' the original. Thus, if used careless, you could end up with a construction such as this:
var a1 = 1;
a();
alert ("var a1 = "+a1);
function a()
{
var a1 = 2;
b();
alert ("var a1 = "+a1);
}
function b()
{
alert ("var a1 = "+a1);
}
Fortunately, your use of clear, descriptive variable names will help you here.
Line 80
if (Folder.name !== /\Resources$/) ...
Improper use of proper Javascript syntax ☺
!== is not a valid comparison operator. Use either == (Test if Equal) or === (Test if Very Equal -- see Does it matter which equals operator (== vs ===) I use in JavaScript comparisons? for some gritty details), and != for Test if Not Equal.
You can compare a string to another but not to a GREP expression. The notation /.../ is reserved for GREP expressions only, for strings you need "..." or '...'. While it's true that some functions may accept both GREP and regular strings, this test does not.
To use a GREP string in a comparison, use the String function match:
if (Folder.name.match(/\\Resources$/)) ...
Note the double end parentheses (one for the enclosing if and one for the match function) and double backslashes, because the backslash is a 'special character' inside a GREP string. (It is special inside a Javascript string as well, so whatever you intended to use, it possibly could be called Improper Syntax #4.)
Will this Fix Everything and Make It Work?
Untested. Without these corrections, your script will not work. With them, it should at least do something (if your logic is sound, your paths exist, your input is right and your Illustrator constants have the correct name).
Provisionally, I'd hazard to say it should work.
Addendum
It took some debugging to find out the real problem .. Debug strategy: inserting alert before suspicious lines, showing values of important variables. Run, wait for results, rinse, repeat.
First off: passing on array as a function parameter seems to have been a Not-Good idea. I found that the array got copied over and over onto itself (or perhaps it was just the result of my tinkering). I think the safer way is to have getFiles return only the newly-added files, and concatenate the result to its current version (i.e., "in" the routine from whence you called getFiles, where it doesn't matter if it was a previous incarnation of getFiles or not). See (I think!) my warning on modifying 'local', 'global', and/or 'passed' variables above.
function getMyFiles( fold, exp ) {
//This is line 80//
if (!fold.name.match (/(\\|\/)Resources$/)) {
var i, temp;
var array = [];
temp = Folder( fold ).getFiles(); // All files and folders…
for ( i = 0; i < temp.length; i++ ) {
if ( temp[i] instanceof File && RegExp( exp ).test( temp[i].fsName ) ){
// alert ('path '+fold+', adding '+temp[i]);
array.push( temp[i] );
};
if ( temp[i] instanceof Folder ) {
array = array.concat (getFiles( temp[i], exp ));
};
};
// alert ('array is '+array.length+'\n'+array.join('\n'));
return array;
};
return [];
};
You would call this function as before in your original recursiveFolders function, but this time don't pass the array but assign it:
function recursiveFolders( fold, exp )
{
var fileList = Array(); // Our matching files…
fileList = getFiles( fold, exp );
// alert ('Filelist is '+fileList.length+'\n'+fileList.join ('\n'));
return fileList;
};
Only when I got that part working, I got the same error you did, per your comment "fold.match is not a function". That took a minute or so of head-scratching. As it turns out, the Javascript parser was right. Initially, the fold argument is a Folder and to get its name, you need fold.name. But look in your own code: you used in the recursive call to itself the argument temp[i].fsName, which is a String! Hence, no name, hence, error.
First, I bluntly converted fold to always-a-String using fold.toString (which works on Folder and String alike), but then I changed my mind and used fold.name for consistency, and call getFiles with the "proper" argument: temp[i] instead of temp[i].fsName. Now it seems to work -- for real. (Said with slightly more confidence.)
I have a function to generate guids for testing:
helpers.guid = function(){
var guid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
return guid;
};
I call it with:
var thisTest.guid1 = helpers.guid();
var thisTest.guid2 = helpers.guid();
The problem is each time I refer to thisTest.guid1 it's a different guid. I need to set the object property to a permanent value and I'm not sure how to do that. I've tried adding a closure but couldn't get it to work.
Edit: to clarify, i need to be able to generate multiple guids and assign each one to a different variable. Right now each time I refer to a variable i get a new guid as it presumably calls the function again and returns a new value. I need "guid1" and "guid2" to be the same values each time then are used.
Question title is much simpler than unnecessarily complicated code example and text with it ... Let's use much simpler code.
var seed = 1 ;
function generate () {
return seed++ ;
}
var a = generate() ;
alert(a + "\n" + a + "\n" + a ) ;
This of course shows "1" three times ... And it will, regardless of is it an object property or a variable. Return value of the function is kept in the memory because it is referenced by the variable a. Object property of course will behave the same:
var a = { b : generate() };
alert( a.b + "\n" + a.b + "\n" + a.b ) ;
This will show "1" three times again. Likewise each call to generate() will yield new value.
var a = {b:generate(), c:generate(), d:generate() };
alert( a.b + "\n" + a.c + "\n" + a.d ) ;
This will output "1", "2" and "3". Each call to function returns a value which is referenced by different object property, thus we have three different values.
If I am understanding correctly you could use 2 functions:
1 - a function to generate the GUID and then store it somewhere, like
in a hidden control somewhere on your form, so you can get it later
2- a function that retrieves the value of your hidden control.
Consider the Code below:
function splicer()
{
var arrayElements = ["elem1","elem2","elem3","elem4"];
for(var index in arrayElements)
{
arrayElements.splice(index,1);
}
alert("Elements: "+arrayElements);
}
The above function is supposed to remove all the elements from the array "arrayElements". But it won't.
Javascript engine maintains the "index" as it is and doesn't mind the array being modified.
People might expect something like "for each" loop that doesn't have this kind of issue
even the following code doesn't seem to work:
function splicer()
{
...
for(var index in arrayElements)
{
arrayElements.splice(index--,1);
}
...
}
even when changing the value of the variable "index" doesn't seem to work.
the changed value is available inside the "for(...){...}" block but, as the loop reaches the next iteration, the value gets reset and continues from the next index as clockwork.
so it seems code like this might be the only solution:
function splicer()
{
var arrayElements = ["elem1","elem2","elem3","elem4"];
for(var index=0;index<arrayElements.length;index++)
{
arrayElements.splice(index--,1);
}
alert("Elements: "+arrayElements);
}
Tested in: Firefox 16 Beta.
But placing a unary Operator inside a "splice()" method seems to be misleading at first sight.
This might be worth considering to the "W3C" or whomever it may concern so that they come up with a nice solution.
You may want to refer to John Resig's array.remove() link.
// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
Try this:
*Splice modifies the original array, hence tge loop skips the alternate values. *
var arrayElements = ["elem1","elem2","elem3","elem4"];
arrayElements.splice(0,arrayElements.length);
alert("Elements: "+arrayElements)
I just saw a video of Nicholas Zakas of Yahoo, at GoogleTalks talking about speeding up your website. One of the things he mentioned was doing loops in reverse order to skip one of two comparisons: for (i = len; i--;) {}
And he said to keep away from JS libraries implementations of for each. Just for fun I thought I'd try it out. Turns out he was wrong.
var array1 = new Array();
var array2 = new Array();
var start = 0;
var finished = 0;
start = (new Date).getTime();
$("#newDivTest").children().each(function(i){
array1[i] = $(this).get(0).id;
});
finished = (new Date).getTime() - start;
alert(finished);
start = (new Date).getTime();
var len = $("#newDivTest").children().length;
for (i = len; i--;) {
array2[i] = $(this).get(0).id;
}
finished = (new Date).getTime() - start;
alert(finished);
newDivTest holds 1000 empty divs with an id starting at "0" and going up to "999". Another note is that $(this).get(0).id is about 3 times faster than $(this).attr("id") for some reason, anyone know why?
For FF3.5, the results are "7" and "45", IE7 gives "30" and "45", Chrome2 gives "4" and "17", Opera10 gives "16" and "16", and lastly Safari4 gives "4" and "16".
So it seems the approach Nicholas is hardest against is actually the faster in almost all instances.
I'm not smart enough to know what's going on behind the scenes for jQuery's each()-method, but it must be doing something right...right?
One flaw in your setup is that your second test will not actually work. You wrote:
for (i = len; i--;) {
array2[i] = $(this).get(0).id;
}
But this is not defined there, so the entire operation will fail. You'd have to do something like:
var children = $("#newDivTest").children();
for (i = children.length; i--;) {
array2[i] = children.get(i).id;
}
And this gets at a more pressing issue than performance: although calls to something like jQuery's .each() function do result in added function calls (and the associated added overhead), they also tend to make it much easier to express what you want the code to do.
Quoting Michael Jackson: "The First Rule of Program Optimization: Don't do it. The Second Rule of Program Optimization (for experts only!): Don't do it yet."
Aren't your tests doing different things?
In the second test this is not the same as the first one.
Slightly off topic and not a direct answer to your main question but, jQuery's each method is implemented like so (jQuery 1.3.2)
jQuery.extend({
/* ... Code taken out for brevity ... */
// args is for internal usage only
each: function( object, callback, args ) {
var name, i = 0, length = object.length;
if ( args ) {
if ( length === undefined ) {
for ( name in object )
if ( callback.apply( object[ name ], args ) === false )
break;
} else
for ( ; i < length; )
if ( callback.apply( object[ i++ ], args ) === false )
break;
// A special, fast, case for the most common use of each
} else {
if ( length === undefined ) {
for ( name in object )
if ( callback.call( object[ name ], name, object[ name ] ) === false )
break;
} else
for ( var value = object[0];
i < length && callback.call( value, i, value ) !== false; value = object[++i] ){}
}
return object;
}
/* ... Code taken out for brevity ... */
);
as you can see, a callback function is applied to each property of object. the jQuery object has a length property defined so will perform the following loop (generally, no args are supplied)
for ( var value = object[0]; i < length && callback.call( value, i, value ) !== false; value = object[++i] ){}
in each iteration, the callback function will increase the scope chain length by 1, thus will take longer to resolve the reference to the object's property.
I notice that your question is "JS looping and populating array. Which is faster?", but your examples are actually testing the speed of various selectors of JQuery, right? You might be interested in checking out :http://mootools.net/slickspeed/
As for "JS looping and populating array. Which is faster?", see here : http://blogs.oracle.com/greimer/resource/loop-test.html