I have difficulty with assigning and retrieving the values of elements in the open array, the array size and dimensions are not fixed so its due to expand or shrink during the iteration. I declare the array as var NODES[[]]; trying to assign, retrieving values and obtaining the length of any dimension in array results wrong values. Especially with the var le = NODES[0].length ; code I 'd expect to see the total length of first dimension.
var NODES =[[]]
scene = editor.scene;
scene.traverse( function(e) {
if ( (e instanceof THREE.Line) && (e.name = 'main line' ) )
{
for (i=0; i<e.geometry.vertices.length; i++){
var x = e.position.x+ e.geometry.vertices[i].x
var y = e.position.y+ e.geometry.vertices[i].y
var z = e.position.z+ e.geometry.vertices[i].z
NODES[node_cnt,0] = x;
NODES[node_cnt,1] = y;
NODES[node_cnt,2] = z;
node_cnt++;
}
cnt++;
};
var le = NODES[0].length ;
EXPECTED RESULT
NODES[0][0] = 10; NODES[0][1] = 20; NODES[0][3] = 30;
NODES[1][0] = 40; NODES[1][1] = 50; NODES[1][3] = 60;
NODES[2][0] = 70; NODES[2][1] = 80; NODES[2][3] = 90;
with `var le = NODES[0].length ;` I expect to see 3 because I'm requesting the length of 1st dimension
This is the javascript interpretation of multi dimensional array, NODES is an array which contains actually 3 array, every array contained in NODES contain a string:
var NODES = [[],[],[]];
for (var i = 0; i < 10 ; i++) {
NODES[0].push(i + 'x');
NODES[1].push(i + 'y');
NODES[2].push(i + 'z');
}
console.log(NODES[0].lenght);
If every contained array should contain one another array the sintax to do this should be:
NODES[0].push([i + 'x']);
Sorry, I'm not understand clearly what mean node_cnt and cnt, but I think you should do something like this:
var NODES =[[],[],[]]
scene = editor.scene;
scene.traverse( function(e) {
if ( (e instanceof THREE.Line) && (e.name = 'main line' ) )
{
for (i=0; i<e.geometry.vertices.length; i++){
var x = e.position.x+ e.geometry.vertices[i].x
var y = e.position.y+ e.geometry.vertices[i].y
var z = e.position.z+ e.geometry.vertices[i].z
NODES[0].push(x);
NODES[1].push(y);
NODES[2].push(z);
node_cnt++;
}
cnt++;
};
var le = NODES[0].length ;
Related
This question already has answers here:
Get an error when I call object's properties in Array
(4 answers)
Closed 3 years ago.
I'm trying to write a script to disable layers in photoshop. So far the first part (first function) works, and it just grabs all the red layers and puts them in an array. Then I call the second function which takes one by one name from the array and passes it to the disabler (showBounds function). However, I'm looking at the input the showBounds receives ("name") and suddenly it stars saying it's getting "undefined". How can this be? what is happening?
var doc = app.activeDocument;
var theLayers = [];
function fillLayerArray(){
// get number of layers;
var ref = new ActionReference();
ref.putEnumerated( charIDToTypeID("Dcmn"), charIDToTypeID("Ordn"), charIDToTypeID("Trgt") );
var applicationDesc = executeActionGet(ref);
var theNumber = applicationDesc.getInteger(stringIDToTypeID("numberOfLayers"));
// process the layers;
//var theOthers = new Array;
for (var m = 0; m <= theNumber; m++) {
var ref = new ActionReference();
ref.putIndex( charIDToTypeID( "Lyr " ), m);
var layerDesc = executeActionGet(ref);
var isBackground = layerDesc.getBoolean(stringIDToTypeID("background"));
var layerSet = typeIDToStringID(layerDesc.getEnumerationValue(stringIDToTypeID("layerSection")));
var theName = layerDesc.getString(stringIDToTypeID('name'));
var theColor = layerDesc.getEnumerationValue(stringIDToTypeID("color"));
globColor = theColor;
if (typeIDToStringID(theColor) == "red" && layerSet != "layerSectionEnd" ) {
theLayers.push(theName);
}
};
hideLayers(theNumber);
//showBounds(doc.layerSets);
}
function hideLayers(theNumber){
for (var i = 0; i <= theLayers.length; i++) {
//app.activeDocument.activeLayer.visible = false;
currentLayerName = theLayers[i];
//alert(currentLayerName)
alert(currentLayerName);
showBounds(doc.layerSets, currentLayerName);
}
}
function showBounds(layerNode, name) {
for (var i=0; i<layerNode.length; i++) {
showBounds(layerNode[i].layerSets);
for(var layerIndex=0; layerIndex < layerNode[i].artLayers.length; layerIndex++) {
var layer=layerNode[i].artLayers[layerIndex];
alert(layer.name + name)
try{
if (layer.name == name) {
layer.visible = 0;
}
}catch(e){
}
}
}
}
fillLayerArray();
You have
i <= theLayers.length
Should be
i < theLayers.length
In hideLayers.
(Also in m <= theNumber .... remember arrays are indexed starting from zero in JS)
I'm not much familiar with javascript, but I faced a need to send and receive big static 2D integer arrays (where values are > 255) as base64 strings (this is essential). At the moment I've came up with this straightforward and inefficient solution converting them element-wise and manually constructing strings, which, as far as I understand, should involve a lot of copying of the data and turns to be very slow.
Can it be done in a more efficient way, if possible without usage of some big side libraries like Node.js, etc?
//----------- serializing/deserializing procedures
//encoding int contours array to be sent as base64 string
function getBase64IntArray(arr) {
var width = arr.length;
//This works given the inner arrays length never changes.
var height = arr[0].length;
//string that would contain data
var str = width.toString()+","+height.toString()+",";
for(var x = 0; x < height; x++) {
for(var y = 0; y < width; y++) {
str = str + arr[x][y].toString() + ",";
}
}
var str64 = btoa(str);
return str64;
}//getBase64IntArray
//deconding this string back to array
function getIntArrayfromBase64(str64) {
var str = atob(str64);
//first occurence of ","
var width_str = str.substr(0,str.indexOf(','));
str = str.substr(str.indexOf(',')+1); // cut the beginning
//again first occurence of ","
var height_str = str.substr(0,str.indexOf(','));
str = str.substr(str.indexOf(',')+1); // cut the beginning
var width = parseInt(width_str);
var height = parseInt(height_str);
//declare new array and fill it
var arr = new Array(height);
var curr_str = "";
for(var x = 0; x < height; x++) {
arr[x] = new Array(width);
for(var y = 0; y < width; y++) {
//first occurence of ","
curr_str = str.substr(0,str.indexOf(','));
// cut the beginning
str = str.substr(str.indexOf(',')+1);
arr[x][y]=parseInt(curr_str);
}
}
return arr;
}// getIntArrayfromBase64
Sending/receiving works:
//----------- example usage
function send(){
//encoding to base64
var arr = [
[1, 2],
[3, 4]
];
var base64 = getBase64IntArray(arr);
webSocket.send(base64);
}
webSocket.onmessage = function(event){
//reading array as base64 string
var arr = getIntArrayfromBase64(event.data);
var width = arr.length;
var height = arr[0].length;
writeResponse("Received "+width+" "+height+" "+arr[0][0]+arr[1][1]);
};
How about going through JSON? JSON will add minimal overhead to the wire format, but the serialization/deserialization will be fast, because it's implemented natively.
function getBase64IntArray(arr) {
return btoa(JSON.stringify(arr))
}
function getIntArrayfromBase64(str64) {
return JSON.parse(atob(str64))
}
I have spent many hours on this irritating problem in my code. I define a class to hold several properties. I then populate those properties into a 2d array. From there, I then attempt to modify random elements in the 2d array. I keep getting the message
"Cannot read property of 'attribute' of undefined"
where attribute is any one of the three attributes in my object. Here is my code:
var table = new Array();
var adjacencyList = new Array();
var cell = function (prop) {
var atrbs = {
x: prop.x,
y: prop.y,
isVisited: prop.isVisited
}
return atrbs;
};
var createTable = function(size){
for(var row = 0; row < size; row++){
table[row] = new Array();
for(var column = 0; column < size; column++){
table[row][column] = new cell({x: row, y: column, isVisited: false});
}
}
};
function print(){
for(var row = 0; row < table.length; row++){
for(var column = 0; column < table[row].length; column++){
console.log(table[row][column]);
}
}
};
var randomizeMaze = function(){
var randomX = Math.floor((Math.random() * table.length));
var randomY = Math.floor((Math.random() * table.length));
var currentCell = table[randomX][randomY];
currentCell.isVisited = true;
adjacencyList.push(currentCell);
while( adjacencyList.length > 0 ) {
currentCell.isVisited = true;
var adjacentNodes = getAdjacentNodes(currentCell);
//randomly select a node to add to path
var nextInPath = adjacentNodes[Math.floor((Math.random() * adjacentNodes.length))];
//add to path to not visit it again
adjacencyList.push.apply(adjacencyList, adjacentNodes);
var removeNode = adjacencyList.indexOf(currentCell);
adjacencyList.splice(removeNode, 1);
//reset currentCell to random cell from resized list
currentCell = adjacencyList[Math.floor((Math.random() * adjacencyList.lenth))];
}
};
function getAdjacentNodes(pCell){
var adjacentNodes = new Array();
//check left
if(pCell.x - 1 >= 0){
var node = table[pCell.x-1][pCell.y];
adjacentNodes.push(node);
adjacencyList.push(node);
}
//check right
if(pCell.x + 1 < table.length){
var node = table[pCell.x+1][pCell.y];
adjacentNodes.push(node);
adjacencyList.push(node);
}
//check top
if(pCell.y - 1 >= 0){
var node = table[pCell.x][pCell.y - 1];
adjacentNodes.push(node);
adjacencyList.push(node);
}
//check bottom
if(pCell.y + 1 < table.length){
var node = table[pCell.x][pCell.y + 1];
adjacentNodes.push(node);
adjacencyList.push(node);
}
return adjacentNodes;
};
createTable(3);
//print();
randomizeMaze();
Whenever I try and access/change any property inside of a cell, namely in the functions 'randomeMaze' and 'getAdjacentNodes', it will throw the error I mentioned. I can print the objects to console, I see the objects as being populated when I debug. Maybe I'm missing something and am going crazy.
Any help would be greatly appreciated.
I have leaflet object _test which looks like this
There are 4050 elements, and for all those elements I tried to run a loop and place label
var a = Object.keys(_test);
console.log(a.length);
j = 0;
for (var i = 0; i < a.length - 1; i++) {
var b = _test[a[i]];
var vdc = L.polygon(b._latlngs);
vdc_name = b.feature.properties.NAME_4;
var labelLocation = new L.LatLng(vdc.getBounds().getCenter().lat, vdc.getBounds().getCenter().lng);
var labelTitle = new L.LabelOverlays(labelLocation, vdc_name);
VDC_labels.addLayer(labelTitle);
console.log(vdc_name, j);
j++}
The output in console for console.log(a.length); is 4050. But the last output of
console.log(vdc_name, j);
is Sidin 1841, which means the loop runs only 1841 times. Can anyone please help me find out what i am doing wrong?
I also tried with this but the result is the same
for (ath in _test) {
var b = _test[ath];
var vdc = L.polygon(b._latlngs);
// console.log(i);
// i++
vdc_name = b.feature.properties.NAME_4; //label content
var labelLocation = new L.LatLng(vdc.getBounds().getCenter().lat, vdc.getBounds().getCenter().lng);
var labelTitle = new L.LabelOverlays(labelLocation, vdc_name);
VDC_labels.addLayer(labelTitle);
}
Solved.
Actually the problem is with the data i.e. in _test object the 1842nd element is a multipolygon unlike all other elements (polygon) so during the access of coordinate in
var b = _test[a[i]];
var vdc = L.polygon(b._latlngs);
b doesnot have the property _latlngs so the loop breaks..
Looking to extend my javascript object, I want to find the minium and maximum of a multicolumn csvfile. I have looked up solutions but I cannot really grasp the right way. I found a solution here: Min and max in multidimensional array but I do not get an output.
My code that I have for now is here:
function import(filename)
{
var f = new File(filename);
var csv = [];
var x = 0;
if (f.open) {
var str = f.readline(); //Skips first line.
while (f.position < f.eof) {
var str = f.readline();
csv.push(str);
}
f.close();
} else {
error("couldn't find the file ("+ filename +")\n");
}
for (var i=(csv.length-1); i>=0; i--) {
var str = csv.join("\n");
var a = csv[i].split(","); // convert strings to array (elements are delimited by a coma)
var date = Date.parse(a[0]);
var newdate = parseFloat(date);
var open = parseFloat(a[1]);
var high = parseFloat(a[2]);
var low = parseFloat(a[3]);
var close = parseFloat(a[4]);
var volume = parseFloat(a[5]);
var volume1000 = volume /= 1000;
var adjusted_close = parseFloat(a[6]);
outlet(0, x++, newdate,open,high,low,close,volume1000,adjusted_close); // store in the coll
}
}
Edit
What if, instead of an array of arrays, you use an array of objects? This assumes you're using underscore.
var outlet=[];
var outletkeys=['newdate','open','high','low','close','volume','volume1000','adjusted_close'];
for (var i=(csv.length-1);i>0; i--) {
var a = csv[i].split(",");
var date = Date.parse(a[0]);
var volume = parseFloat(a[5],10);
outlet.push( _.object(outletkeys, [parseFloat(date,10) , parseFloat(a[1],10) , parseFloat(a[2],10) , parseFloat(a[3],10) , parseFloat(a[4],10) , parseFloat(a[5],10) , volume /= 1000 , parseFloat(a[6],10) ]) );
}
Then the array of the column 'open' would be
_.pluck(outlet,'open');
And the minimum it
_.min(_.pluck(outlet,'open'));
Edit2
Let's forget about underscore for now. I believe you need to get the maximum value on the second column, which is what you put in your open variable.
¿Would it help if you could have that value right after the for loop? For example
var maxopen=0;
for (var i=(csv.length-1); i>=0; i--) {
var a = csv[i].split(",");
var date = Date.parse(a[0]);
var newdate = parseFloat(date);
var open = parseFloat(a[1]);
maxopen=(open>maxopen)? open : maxopen; // open overwrites the max if it greater
...
...
outlet(0, x++, newdate,open,high,low,close,volume1000,adjusted_close);
}
console.log('Maximum of open is',maxopen);