Object's push method not working properly [duplicate] - javascript

This question already has answers here:
Javascript Object push() function
(10 answers)
Closed 8 years ago.
I have a object for which i am using push method and it gives me length one more than expected.
var Object=[];
var temp = {};
var j=0;
while(j<2){
temp.id= j+1;
//other properties setting
Object.push(temp);
j++;
}
console.log(Object.length);
gives me 3. Also I see three object values, first as empty second has id =1 and third has id =2.

.push is a function of Array and not Object and don't use variable names that cause ambiguity.
Use:
var arr = [];
var temp = {};
var j = 0;
while (j < 2) {
temp.id = j + 1;
//other properties setting
arr.push(temp);
j++;
}
console.log(arr.length);

Related

When using strings with numbers at the start in an array key (Indesign 2017, extendscript) they don't get added to the array

Observe:
var groupedLinks = new Array;
for(var i = 0; i < 5; i++) {
linkName = "59notgonnawork" + i;
groupedLinks[linkName] = new Array;
}
I would have expected the result to be the array groupedLinks to be filled up with 5 new keys, the value would be 5 empty arrays.
The actual result in extendscript would be ... grouplinks ... empty.
If I would change this example to be:
var groupedLinks = new Array;
for(var i = 0; i < 5; i++) {
linkName = "notgonnawork" + i;
groupedLinks[linkName] = new Array;
}
It would work perfectly. The only change is the missing "59" at the start of the string used for the array key.
Note that this works perfectly when I run it in console for chrome or firefox. It seems to be indesign and/or extendscript fooling around.
Anything have any ideas why ? I've meanwhile worked around the problem but I'm intrigued.
I would have expected the result to be the array groupedLinks to be filled up with 5 new keys, the value would be 5 empty arrays.
That's exactly what it does, but the way you're viewing the data is likely concealing it because you're not using the proper data structure. Also, property access won't work without using [] because identifiers may not start with a number, so you'd need:
groupedLinks["59notgonnawork0"]
What you're doing isn't meant for arrays, which are expecting sequential numeric indices (though they can technically be assigned other properties too). The type of structure you should be using is a plain object instead.
var groupedLinks = {};
for(var i = 0; i < 5; i++) {
const linkName = "59notgonnawork" + i;
groupedLinks[linkName] = new Array; // Array? plain Object? Depends on its use.
}
Why not trying to push the value in the array on each iteration.
var groupedLinks = new Array;
for(var i = 0; i < 5; i++) {
linkName = "59notgonnawork" + i;
groupedLinks.push(linkName);
}
ExtendScript Arrays are great for stocking data per indeces. If you need key/values objects, why not use… Objects ?
var groupedLinks = {};
for(var i = 0; i < 5; i++) {
linkName = "59notgonnawork" + i;
groupedLinks[linkName] = "Whatever…";
}
alert( groupedLinks["59notgonnawork0" ] ); //"Whatever…"

Get value from dynamic variable [duplicate]

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 5 years ago.
I have variables such as app.figures.data[0].user.x0 , app.figures.data[0].user.y1, and app.figures.data[0].user.d2. These variables were assigned values.
There are a dynamic number of these variables following the order of incrementing the final number in the variable (ie: The next variable after app.figures.data[0].user.d2 is app.figures.data[0].user.x3).
I am trying to determine an efficient way to get the value of each variable dynamically in a loop.
for(j = 0; j < len; j++){
var x = 'x' + j;
j++;
var y = 'y' + j;
j++;
var d = 'd' + j;
var dresult = app.figures.data[0].user.d;
}
I need the value of dresult as it was for app.figures.data[0].user.d2. For example, app.figures.data[0].user.d2 is 23 so dresult should be 23 on that iteration.
I am new to JS so any suggestions are appreciated.
Would the [] operator work for you?
for (let j = 2; j < len; j += 3) {
let dresult = app.figures.data[0].user['d' + j];
}
var values=["x0","y1","d2"]. map(el=>this[el],app.figures.data[0].user);
It will map the keys to their corresponding values.
You can put that in a loop:
for(var i=0; i<100;i+=3){
var values=["x","y","d"]. map((el,id)=>this[el+(i+id)],app.figures.data[0].user);
values.forEach(console.log);//just an example case
}
Some explanations: i is the counter, incremented by 3, stops at 102. el is an array element, so "y", and id is the index in that array. this is the user object. So this[el+(i+id)] gets the value of this objects property.
By the way dynamic variable names are really bad style and will cause many bugs. May change your code to work without it.

Print all the names of keys stored in localStorage html [duplicate]

This question already has answers here:
Get HTML5 localStorage keys
(15 answers)
Closed 7 years ago.
I'm trying to print the names of all the keys stored in localStorage with each key in a separate line. This is my code:
function viewsaved(){
$('#saved').show();
var stuffsaved = Object.keys(localStorage);
var splitit = stuffsaved.split(',');
for (var i = 0 ; i < splitit.length ; i++ ){
$('#saved').append(splitit[i]+"<br>");
}
}
when I call the function, it does nothing.
How do you do this properly?
Object.keys returns an array, not a string. Just modify slightly:
var stuffsaved = Object.keys(localStorage);
for (var i = 0 ; i < stuffsaved.length ; i++ ) {
$('#saved').append(stuffsaved[i]+"<br>");
}
If you have or expect a lot of keys, I would suggest building the list in a temporary variable first to avoid frequent DOM update, for example:
var keys = Object.keys(localStorage);
var list = "";
for (var i = 0 ; i < keys.length ; i++ ) {
list += keys[i] + "<br>";
}
$('#saved').append(list);

count array skipping the unique values [duplicate]

This question already has answers here:
Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array
(97 answers)
Closed 8 years ago.
I'm like to count the total values in my array but I like to skip the same value
my array example, my real array will have about 1000 values.
json2=[aaa,aaa,aaa,aaa,bbb,bbb,bbb,ccc,ccc,ccc,ccc,ccc,ddd,ddd,ddd,eee,eee,fff];
and i want my count result to be
var countBoxID=6;
i only got
for(i in json2){
countBOXID ++
}
You can make use of this function:
function GetUnique(inputArray)
{
var outputArray = [];
for (var i = 0; i < inputArray.length; i++)
{
if ((jQuery.inArray(inputArray[i], outputArray)) == -1)
{
outputArray.push(inputArray[i]);
}
}
return outputArray;
}

Using numbers for names of javascript object elements

Is the following code valid?
var i;
var objs={};
for (i=0; i <10; i++)
{
objs.i=new FooObject();
}
alert(objs.4.someMethod());
If not, how should it be rewritten to accomplish what I want?
You should edit your code as following:
var i;
var objs = {};
for (i = 0; i < 10; i++) {
objs[i] = new FooObject();
}
alert(objs[4].someMethod());
var i;
var objs = new Array();
for(i = 0; i < 10; i++)
{
objs.push(new FooObject());
}
objs[4].someMethod();
You cannot use numericals for variable names 1. If you want to reference an item by a numerical value, use an array 2. You can then access items by their key in the array. If you want to cycle through, you can use the for...in option 3. It won't matter if your keys are sequential and contiguous:
var x;
var myItems = new Array();
myItems[0] = "Foo";
myItems[9] = "Bar";
myItems[5] = "Fiz";
for (x in myItems) {
alert(myItems[x]);
}
1 http://www.w3schools.com/js/js_variables.asp
2 http://www.w3schools.com/js/js_obj_array.asp
3 http://www.w3schools.com/js/tryit.asp?filename=tryjs_array_for_in
You can't use numbers as variable names, because straight up numbers exist as their own object set in Javascript (i.e, you could think of 4 as already being a global variable that you can't override).

Categories