Create variables from a JavaScript array of filenames
I have a JavaScript array with the filenames (and their directory location) in it (originally gotten by using PHP to create a PHP array of files in the directory and then converted to a JS array). I'd like to use this array to generate individual variables with the same name as their value.
For example, this is one of the array values, "collada/basement/zones/basementPCroom.dae". I'd like to use this to create a variable called "basementPCroom" which holds the value "collada/basement/zones/basementPCroom.dae". And the same with all other values in the array.
The reason I want to do this is because changing each individually every time I add or remove files would take forever, and I need them to have those specific names so that I can f开发者_StackOverflow社区ind what I'm looking for easily later.
Thanks for your help!
Below is the code leading up to this:
<?php
$zones = glob('collada/first/zones/*dae');
?>
var zones = <?php echo json_encode($zones) ?>;
One way is to do it like this (there might be more optimum ways to do this):
var filenames = filenames || {};
for(var i = 0, len = array.length; i < len; i++) {
filenames[getName(array[i])] = array[i];
}
function getName(str) {
var parts = str.split('/');
return parts[parts.length-1].split('.')[0];
}
Update: Merged my updates to create a object to hold fielnames instead of polluting global namesapce.
If you wanted to do the work server-side you could do something like this:
$zoneArray = glob('whatever');
//grab keys
$grabFileName = function($val){
return substring($val, strrchar($val, '/'), strchar($val, '.'));
}
$zoneKeys = array_map($grabFileName, $zoneArray);
//apply keys to array
$zoneHash = array_combine($zoneKeys, $zoneArray);
//associative arrays become objects
json_encode($zoneHash);
Don't try to "create variables". Instead put everything in an object, aka associative array:
var paths = {};
paths[a_file_name] = its_directory;
This uses the fact that you can use bracket notation instead of dot notation to acess an object in Javascript
obj['foo']
//is the same as
obj.foo
精彩评论