Copy link to clipboard
Copied
I'd like to save the x,y position array of an object for reuse later. I can save the "position" to the note
[49.8303615172063,11.4548352296533]
but when accessed by the code below it does not act like an array. What am I doing wrong?
Hi @rcraighead,
The note is stored as a sting.
The split function return numbers as a string. Try to use conversion as below
var coords = (selection[0].note);
var myArray = coords.split(',');
selection[0].position = [Number(myArray[0]), Number(myArray[1])];
Also, you can save JSON object if required.
{
x: 49.8303615172063,
y: 11.4548352296533
}
for (var i = 0; i < myArray.length; i++) {
alert(typeof myArray[i]); // "string"
}
try {
selection[0].position = ["44", "55"]; // This is what you're doing:
} catch (err) {
// Which results in an error because you can't apply strings to numeric values:
alert(err); // "Error: Point value expected"
}
As Charu points out you'd have to convert them to typeof Numbers before being able to apply. Just as an extra trick, you can do this in all sorts of different ways in native JS:
~~"3.14"
...
Saving you using note, split and converting, you could save position in your own defined array property. E.g.
selection[0].position1 = selection[0].position;
// do something
selection[0].position = selection[0].position1;
Copy link to clipboard
Copied
Hi @rcraighead,
The note is stored as a sting.
The split function return numbers as a string. Try to use conversion as below
var coords = (selection[0].note);
var myArray = coords.split(',');
selection[0].position = [Number(myArray[0]), Number(myArray[1])];
Also, you can save JSON object if required.
{
x: 49.8303615172063,
y: 11.4548352296533
}
Copy link to clipboard
Copied
for (var i = 0; i < myArray.length; i++) {
alert(typeof myArray[i]); // "string"
}
try {
selection[0].position = ["44", "55"]; // This is what you're doing:
} catch (err) {
// Which results in an error because you can't apply strings to numeric values:
alert(err); // "Error: Point value expected"
}
As Charu points out you'd have to convert them to typeof Numbers before being able to apply. Just as an extra trick, you can do this in all sorts of different ways in native JS:
~~"3.14" // 3
+"3.14" // 3.14 > This is what I normally always use, but it can hurt readability
"3.14"*1 // 3.14 > This can be the fastest, most performant way to convert from String > Number
Number("3.14") // 3.14 > This is the most reliable for largest integers
Math.round("3.14") // 3 > Math.floor, ceil, and round accept either string or number
Copy link to clipboard
Copied
Saving you using note, split and converting, you could save position in your own defined array property. E.g.
selection[0].position1 = selection[0].position;
// do something
selection[0].position = selection[0].position1;
Copy link to clipboard
Copied
Thank you all for the great help!