Leaflet angular. can i write a loop inside an array? [duplicate] - javascript

How can I add an object to an array (in javascript or jquery)?
For example, what is the problem with this code?
function() {
var a = new array();
var b = new object();
a[0] = b;
}
I would like to use this code to save many objects in the array of function1 and call function2 to use the object in the array.
How can I save an object in an array?
How can I put an object in an array and save it to a variable?

Put anything into an array using Array.push().
var a=[], b={};
a.push(b);
// a[0] === b;
Extra information on Arrays
Add more than one item at a time
var x = ['a'];
x.push('b', 'c');
// x = ['a', 'b', 'c']
Add items to the beginning of an array
var x = ['c', 'd'];
x.unshift('a', 'b');
// x = ['a', 'b', 'c', 'd']
Add the contents of one array to another
var x = ['a', 'b', 'c'];
var y = ['d', 'e', 'f'];
x.push.apply(x, y);
// x = ['a', 'b', 'c', 'd', 'e', 'f']
// y = ['d', 'e', 'f'] (remains unchanged)
Create a new array from the contents of two arrays
var x = ['a', 'b', 'c'];
var y = ['d', 'e', 'f'];
var z = x.concat(y);
// x = ['a', 'b', 'c'] (remains unchanged)
// y = ['d', 'e', 'f'] (remains unchanged)
// z = ['a', 'b', 'c', 'd', 'e', 'f']

var years = [];
for (i= 2015;i<=2030;i=i+1){
years.push({operator : i})
}
here array years is having values like
years[0]={operator:2015}
years[1]={operator:2016}
it continues like this.

First of all, there is no object or array. There are Object and Array. Secondly, you can do that:
a = new Array();
b = new Object();
a[0] = b;
Now a will be an array with b as its only element.

Using ES6 notation, you can do something like this:
For appending you can use the spread operator like this:
var arr1 = [1,2,3]
var obj = 4
var newData = [...arr1, obj] // [1,2,3,4]
console.log(newData);

JavaScript is case-sensitive. Calling new array() and new object() will throw a ReferenceError since they don't exist.
It's better to avoid new Array() due to its error-prone behavior.
Instead, assign the new array with = [val1, val2, val_n]. For objects, use = {}.
There are many ways when it comes to extending an array (as shown in John's answer) but the safest way would be just to use concat instead of push. concat returns a new array, leaving the original array untouched. push mutates the calling array which should be avoided, especially if the array is globally defined.
It's also a good practice to freeze the object as well as the new array in order to avoid unintended mutations. A frozen object is neither mutable nor extensible (shallowly).
Applying those points and to answer your two questions, you could define a function like this:
function appendObjTo(thatArray, newObj) {
const frozenObj = Object.freeze(newObj);
return Object.freeze(thatArray.concat(frozenObj));
}
Usage:
// Given
const myArray = ["A", "B"];
// "save it to a variable"
const newArray = appendObjTo(myArray, {hello: "world!"});
// returns: ["A", "B", {hello: "world!"}]. myArray did not change.

/* array literal */
var aData = [];
/* object constructur */
function Person(firstname, lastname) {
this.firstname = firstname;
this.lastname = lastname;
this.fullname = function() {
// return (this.firstname + " " + this.lastname);
return (`${this.firstname} ${this.lastname}`); // es6 template string
};
}
/* store object into array */
aData[aData.length] = new Person("Java", "Script"); // aData[0]
aData.push(new Person("John", "Doe"));
aData.push(new Person("Anna", "Smith"));
aData.push(new Person("Black", "Pearl"));
aData[aData.length] = new Person("stack", "overflow"); // aData[4]
/* loop array */
for (var i in aData) {
alert(aData[i].fullname());
}
/* convert array of object into string json */
var jsonString = JSON.stringify(aData);
document.write(jsonString);
Push object into array

With push you can even add multiple objects to an array
let myArray = [];
myArray.push(
{name:"James", dataType:TYPES.VarChar, Value: body.Name},
{name:"Boo", dataType:TYPES.VarChar, Value: body.Name},
{name:"Alina", dataType:TYPES.VarChar, Value: body.Name}
);

Expanding Gabi Purcaru's answer to include an answer to number 2.
a = new Array();
b = new Object();
a[0] = b;
var c = a[0]; // c is now the object we inserted into a...

obejct is clearly a typo. But both object and array need capital letters.
You can use short hands for new Array and new Object these are [] and {}
You can push data into the array using .push. This adds it to the end of the array. or you can set an index to contain the data.
function saveToArray() {
var o = {};
o.foo = 42;
var arr = [];
arr.push(o);
return arr;
}
function other() {
var arr = saveToArray();
alert(arr[0]);
}
other();

You can use with Spread Operator (...) like this:
let arr = [{num: 1, char: "a"}, {num: 2, char: "b"}];
arr = [...arr,{num: 3, char: "c"}];
//...arr --> spread operator
console.log(arr);

On alternativ answer is this.
if you have and array like this: var contacts = [bob, mary];
and you want to put another array in this array, you can do that in this way:
Declare the function constructor
function add (firstName,lastName,email,phoneNumber) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.phoneNumber = phoneNumber;
}
make the object from the function:
var add1 = new add("Alba","Fas","Des#gmail.com","[098] 654365364");
and add the object in to the array:
contacts[contacts.length] = add1;

a=[];
a.push(['b','c','d','e','f']);

The way I made object creator with auto list:
var list = [];
function saveToArray(x) {
list.push(x);
};
function newObject () {
saveToArray(this);
};

Performance
Today 2020.12.04 I perform tests on MacOs HighSierra 10.13.6 on Chrome v86, Safari v13.1.2 and Firefox v83 for chosen solutions.
Results
For all browsers
in-place solution based on length (B) is fastest for small arrays, and in Firefox for big too and for Chrome and Safari is fast
in-place solution based on push (A) is fastest for big arrays on Chrome and Safari, and fast for Firefox and small arrays
in-place solution C is slow for big arrays and medium fast for small
non-in-place solutions D and E are slow for big arrays
non-in-place solutions E,F and D(on Firefox) are slow for small arrays
Details
I perform 2 tests cases:
for small array with 10 elements - you can run it HERE
for big array with 1M elements - you can run it HERE
Below snippet presents differences between solutions
A,
B,
C,
D,
E,
F
PS: Answer B was deleted - but actually it was the first answer which use this technique so if you have access to see it please click on "undelete".
// https://stackoverflow.com/a/6254088/860099
function A(a,o) {
a.push(o);
return a;
}
// https://stackoverflow.com/a/47506893/860099
function B(a,o) {
a[a.length] = o;
return a;
}
// https://stackoverflow.com/a/6254088/860099
function C(a,o) {
return a.concat(o);
}
// https://stackoverflow.com/a/50933891/860099
function D(a,o) {
return [...a,o];
}
// https://stackoverflow.com/a/42428064/860099
function E(a,o) {
const frozenObj = Object.freeze(o);
return Object.freeze(a.concat(frozenObj));
}
// https://stackoverflow.com/a/6254088/860099
function F(a,o) {
a.unshift(o);
return a;
}
// -------
// TEST
// -------
[A,B,C,D,E,F].map(f=> {
console.log(`${f.name} ${JSON.stringify(f([1,2],{}))}`)
})
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"> </script>
This shippet only presents functions used in performance tests - it not perform tests itself!
And here are example results for chrome

You are running into a scope problem if you use your code as such. You have to declare it outside the functions if you plan to use it between them (or if calling, pass it as a parameter).
var a = new Array();
var b = new Object();
function first() {
a.push(b);
// Alternatively, a[a.length] = b
// both methods work fine
}
function second() {
var c = a[0];
}
// code
first();
// more code
second();
// even more code

Related

I wrote a function to merge two arrays into a single array but I'm getting "Cannot read properties of undefined"

I am trying to take 2 arrays and merge them into one new array that will combine the objects of each array. I understand how to combine 2 arrays into 1 large one, but I'm having trouble combining the actual objects into a new object within that array. An example of the input and intended output I am trying to get is listed below:
Given arrays:
array1 = ['1','2','3'];
array2 = ['a','b','c'];
New outputted array should be:
array3 = ['1a','2b','3c'];
Here is what i have attempted to do so far. In this example, I am trying to create the deck of cards needed to play a game of euchre (should have the cards 9, 10, Jack, Queen, and Ace and the suits of Clubs, Diamonds, Hearts, and Spades for each card for a total of 24 card combinations). I created 2 arrays (one for the card 'value' and one for the card 'suits.' For my function, I am passing both of these decks into a for loop that will ideally append the object of the 'suits' array to the end of the 'values' array. This new list is then passed into the empty 'deck' array to return the new array. However, I am getting and "Uncaught TypeError: Cannot read properties of undefined (reading 'length')." This is occuring at the beginning of my function 'createDeck' and when I try to call the function in the console log statement at the bottom. Any assistance in understanding the logic I would need to use to combine these arrays would be greatly appreciated as I am just beginning to work with functions and arrays.
const values = ['9','10', 'J', 'Q', 'K','A'];
const suits = ['C', 'D', 'H', 'S'];
function createDeck(values, suits) {
let deck = [];
for (let i = 0; i < suits.length; i++) {
for (let x = 0; x < values.length; x++) {
let card = {Value: values[x], Suit: suits[i]};
deck.push(card);
}
}
return deck;
}
console.log(createDeck());
try to declare a new array and in the for loop do
array[i] = values[i] + suits[i]
maybe you need to add "" in the array with strings
You can create a new array with the map method.
const values = ['1','2', '3'];
const suits = ['a', 'b', 'c'];
function createDeck() {
let customArray = [];
// check for equality of array lengths
if (values.length === suits.length) {
// create a new array with the map method
customArray = values.map((value, index) => {
return value + suits[index]
})
}
return customArray;
}
console.log(createDeck())
Basically you can use Array.prototype.map() method to achieve your expected results. Length of arrays is assumed equal to each other. A sample code is given as below:
array1 = ['1','2','3'];
array2 = ['a','b','c'];
combineArrays = (arr1,arr2) => {
const arr = arr1.map((elem,index)=> {
elem += arr2[index];
return elem
})
return arr
}
console.log(combineArrays(array1, array2)) // ['1a','2b','3c']
For loop version is:
array1 = ['1','2', '3']
array2 = ['a', 'b', 'c']
combineArrays = (arr1,arr2) => {
const deck = []
for(i=0; i<arr1.length; i++) {
deck.push(arr1[i] + arr2[i])
}
return deck
}
console.log(combineArrays(array1, array2)) // ['1a','2b','3c']

How to create an associative array in JavaScript literal notation

I understand that there are no associative arrays in JavaScript, only objects.
However I can create an array with string keys using bracket notation like this:
var myArray = [];
myArray['a'] = 200;
myArray['b'] = 300;
console.log(myArray); // Prints [a: 200, b: 300]
So I want to do the exact same thing without using bracket notation:
var myNewArray = [a: 200, b: 300]; // I am getting error - Unexpected token:
This does not work either:
var myNewArray = ['a': 200, 'b': 300]; // Same error. Why can I not create?
JavaScript has no associative arrays, just objects. Even JavaScript arrays are basically just objects, just with the special thing that the property names are numbers (0,1,...).
So look at your code first:
var myArray = []; // Creating a new array object
myArray['a'] = 200; // Setting the attribute a to 200
myArray['b'] = 300; // Setting the attribute b to 300
It's important to understand that myArray['a'] = 200; is identical to myArray.a = 200;!
So to start with what you want:
You can't create a JavaScript array and pass no number attributes to it in one statement.
But this is probably not what you need! Probably you just need a JavaScript object, what is basically the same as an associative array, dictionary, or map in other languages: It maps strings to values. And that can be done easily:
var myObj = {a: 200, b: 300};
But it's important to understand that this differs slightly from what you did. myObj instanceof Array will return false, because myObj is not an ancestor from Array in the prototype chain.
You can use Map:
var arr = new Map([
['key1', 'User'],
['key2', 'Guest'],
['key3', 'Admin'],
]);
var res = arr.get('key2');
console.log(res); // The value is 'Guest'
You want to use an object in this case
var myObject = {'a' : 200, 'b' : 300 };
This answer links to a more in-depth explanation: How to do associative array/hashing in JavaScript
Well, you are creating an array, which is in fact an object:
var arr = [];
arr.map;
// function(..)
arr['map'];
// function(..)
arr['a'] = 5;
console.log(arr instanceof Object); // true
You can add fields and functions to arr. It does not "insert" them into the array though (like arr.push(...)).
You can refer to an object fields with the [] syntax.
I achieved this by using objects. Your create an object, and loop through using for in loop. each x will be the index and holder[x] will be the value. an example is below.
var test = {'hello':'world','hello2':'world2'}
for(let x in holder)
{
let inxed = x;
let value = holder[x]
console.log('index ' + x + ' has value of ' + value)
}
Associate array is an array indexed with name similar to an object instead of numbers like in regular array. You can create an associative array in the following way:
var arr = new Array(); // OR var arr = [];
arr['name'] = 'david'
arr['age'] = 23;
console.log(arr['name']);
You can do what you wanted to do this way:
myNewArray = new Array ({'a' : 200, 'b' : 300})

Splice confusion

I've been going through the rot.js tutorial located here and I'm making sense of the majority of the examples.
However, I'm confused by one line of code and I was hoping someone could explain what's going on.
This is in the Game._generateBoxes function toward the bottom of the page:
var key = freeCells.splice(index, 1)[0];
I understand that it's removing one element from location index from the freeCells array and assigning it to key. I don't understand what the [0] is doing at the end. I tried removing it and it appeared to function normally. What is this accomplishing?
var key = freeCells.splice(index, 1);
… assigns an array with one member to key.
var key = freeCells.splice(index, 1)[0];
… assigns the value of the member of the aforementioned array and then discards the array.
var index = 1;
function one () {
var freeCells = ['a', 'b', 'c']
var key = freeCells.splice(index, 1)[0];
alert(typeof key);
}
function two () {
var freeCells = ['a', 'b', 'c']
var key = freeCells.splice(index, 1);
alert(typeof key);
}
one(); two();

Create a dynamic nested object from array of properties

This sounds like a simple task, but I can't quite figure it out: I have an array :
var array = ['opt1','sub1','subsub1','subsubsub1']
From that I want to generate the following objects:
{
opt1:{
sub1:{
subsub1:{
subsubsub1:{}
}
}
}
}
I have a way to do it, making a string and using eval, but I'm looking to avoid that, any idea?
You could use reduce:
var array = ['opt1','sub1','subsub1','subsubsub1'];
var object = {};
array.reduce(function(o, s) { return o[s] = {}; }, object);
console.log(object);
But this was only introduced in ECMAScript 5.1, so it won't be supported in some older browsers. If you want something that will be supported by legacy browsers, you could use the polyfill technique described in the MDN article above, or a simple for-loop, like this:
var array = ['opt1','sub1','subsub1','subsubsub1'];
var object = {}, o = object;
for(var i = 0; i < array.length; i++) {
o = o[array[i]] = {};
}
console.log(object);
You can use reduceRight to transform the array into a 'chain' of objects:
const array = ['a', 'b', 'c'];
const object = array.reduceRight((obj, next) => ({[next]: obj}), {});
// Example:
console.log(object); // {"a":{"b":{"c":{}}}}
you could use lodash set function
_.set(yourObject, 'a.b.c')
You can use the following Function
function arr2nestedObject(myArray){
var cp_myArray = myArray;
var lastobj = {};
while(cp_myArray.length>0){
newobj = {};
var prop = cp_myArray.pop();
newobj[prop] = lastobj;
lastobj = newobj;
}
return lastobj;
}
The following code:
var myArray = ["personal-information", "address", "street",'Great-Success'];
console.log(JSON.stringify(arr2nestedObject(myArray),undefined,2));
Would Produce the Following Output:
{
"personal-information": {
"address": {
"street": {
"Great-Success": {}
}
}
}
}
Please let me know if that was what you meant.
Kind Regards.
As #p.s.w.g answer is a very good answer with pure js, but if you want an alternative with in a descriptive and functional way of that and set a value for final nested prop, you can use ramdajs assocPath https://ramdajs.com/docs/#assocPath like below:
var array = ['opt1','sub1','subsub1','subsubsub1'];
R.assocPath(array, "the value", {});
more details:
Makes a shallow clone of an object, setting or overriding the nodes
required to create the given path, and placing the specific value at
the tail end of that path. Note that this copies and flattens
prototype properties onto the new object as well. All non-primitive
properties are copied by reference.
examples:
R.assocPath(['a', 'b', 'c'], 42, {a: {b: {c: 0}}}); //=> {a: {b: {c: 42}}}
// Any missing or non-object keys in path will be overridden
R.assocPath(['a', 'b', 'c'], 42, {a: 5}); //=> {a: {b: {c: 42}}}

How to add an object to an array

How can I add an object to an array (in javascript or jquery)?
For example, what is the problem with this code?
function() {
var a = new array();
var b = new object();
a[0] = b;
}
I would like to use this code to save many objects in the array of function1 and call function2 to use the object in the array.
How can I save an object in an array?
How can I put an object in an array and save it to a variable?
Put anything into an array using Array.push().
var a=[], b={};
a.push(b);
// a[0] === b;
Extra information on Arrays
Add more than one item at a time
var x = ['a'];
x.push('b', 'c');
// x = ['a', 'b', 'c']
Add items to the beginning of an array
var x = ['c', 'd'];
x.unshift('a', 'b');
// x = ['a', 'b', 'c', 'd']
Add the contents of one array to another
var x = ['a', 'b', 'c'];
var y = ['d', 'e', 'f'];
x.push.apply(x, y);
// x = ['a', 'b', 'c', 'd', 'e', 'f']
// y = ['d', 'e', 'f'] (remains unchanged)
Create a new array from the contents of two arrays
var x = ['a', 'b', 'c'];
var y = ['d', 'e', 'f'];
var z = x.concat(y);
// x = ['a', 'b', 'c'] (remains unchanged)
// y = ['d', 'e', 'f'] (remains unchanged)
// z = ['a', 'b', 'c', 'd', 'e', 'f']
var years = [];
for (i= 2015;i<=2030;i=i+1){
years.push({operator : i})
}
here array years is having values like
years[0]={operator:2015}
years[1]={operator:2016}
it continues like this.
First of all, there is no object or array. There are Object and Array. Secondly, you can do that:
a = new Array();
b = new Object();
a[0] = b;
Now a will be an array with b as its only element.
Using ES6 notation, you can do something like this:
For appending you can use the spread operator like this:
var arr1 = [1,2,3]
var obj = 4
var newData = [...arr1, obj] // [1,2,3,4]
console.log(newData);
JavaScript is case-sensitive. Calling new array() and new object() will throw a ReferenceError since they don't exist.
It's better to avoid new Array() due to its error-prone behavior.
Instead, assign the new array with = [val1, val2, val_n]. For objects, use = {}.
There are many ways when it comes to extending an array (as shown in John's answer) but the safest way would be just to use concat instead of push. concat returns a new array, leaving the original array untouched. push mutates the calling array which should be avoided, especially if the array is globally defined.
It's also a good practice to freeze the object as well as the new array in order to avoid unintended mutations. A frozen object is neither mutable nor extensible (shallowly).
Applying those points and to answer your two questions, you could define a function like this:
function appendObjTo(thatArray, newObj) {
const frozenObj = Object.freeze(newObj);
return Object.freeze(thatArray.concat(frozenObj));
}
Usage:
// Given
const myArray = ["A", "B"];
// "save it to a variable"
const newArray = appendObjTo(myArray, {hello: "world!"});
// returns: ["A", "B", {hello: "world!"}]. myArray did not change.
/* array literal */
var aData = [];
/* object constructur */
function Person(firstname, lastname) {
this.firstname = firstname;
this.lastname = lastname;
this.fullname = function() {
// return (this.firstname + " " + this.lastname);
return (`${this.firstname} ${this.lastname}`); // es6 template string
};
}
/* store object into array */
aData[aData.length] = new Person("Java", "Script"); // aData[0]
aData.push(new Person("John", "Doe"));
aData.push(new Person("Anna", "Smith"));
aData.push(new Person("Black", "Pearl"));
aData[aData.length] = new Person("stack", "overflow"); // aData[4]
/* loop array */
for (var i in aData) {
alert(aData[i].fullname());
}
/* convert array of object into string json */
var jsonString = JSON.stringify(aData);
document.write(jsonString);
Push object into array
With push you can even add multiple objects to an array
let myArray = [];
myArray.push(
{name:"James", dataType:TYPES.VarChar, Value: body.Name},
{name:"Boo", dataType:TYPES.VarChar, Value: body.Name},
{name:"Alina", dataType:TYPES.VarChar, Value: body.Name}
);
Expanding Gabi Purcaru's answer to include an answer to number 2.
a = new Array();
b = new Object();
a[0] = b;
var c = a[0]; // c is now the object we inserted into a...
obejct is clearly a typo. But both object and array need capital letters.
You can use short hands for new Array and new Object these are [] and {}
You can push data into the array using .push. This adds it to the end of the array. or you can set an index to contain the data.
function saveToArray() {
var o = {};
o.foo = 42;
var arr = [];
arr.push(o);
return arr;
}
function other() {
var arr = saveToArray();
alert(arr[0]);
}
other();
You can use with Spread Operator (...) like this:
let arr = [{num: 1, char: "a"}, {num: 2, char: "b"}];
arr = [...arr,{num: 3, char: "c"}];
//...arr --> spread operator
console.log(arr);
On alternativ answer is this.
if you have and array like this: var contacts = [bob, mary];
and you want to put another array in this array, you can do that in this way:
Declare the function constructor
function add (firstName,lastName,email,phoneNumber) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.phoneNumber = phoneNumber;
}
make the object from the function:
var add1 = new add("Alba","Fas","Des#gmail.com","[098] 654365364");
and add the object in to the array:
contacts[contacts.length] = add1;
a=[];
a.push(['b','c','d','e','f']);
The way I made object creator with auto list:
var list = [];
function saveToArray(x) {
list.push(x);
};
function newObject () {
saveToArray(this);
};
Performance
Today 2020.12.04 I perform tests on MacOs HighSierra 10.13.6 on Chrome v86, Safari v13.1.2 and Firefox v83 for chosen solutions.
Results
For all browsers
in-place solution based on length (B) is fastest for small arrays, and in Firefox for big too and for Chrome and Safari is fast
in-place solution based on push (A) is fastest for big arrays on Chrome and Safari, and fast for Firefox and small arrays
in-place solution C is slow for big arrays and medium fast for small
non-in-place solutions D and E are slow for big arrays
non-in-place solutions E,F and D(on Firefox) are slow for small arrays
Details
I perform 2 tests cases:
for small array with 10 elements - you can run it HERE
for big array with 1M elements - you can run it HERE
Below snippet presents differences between solutions
A,
B,
C,
D,
E,
F
PS: Answer B was deleted - but actually it was the first answer which use this technique so if you have access to see it please click on "undelete".
// https://stackoverflow.com/a/6254088/860099
function A(a,o) {
a.push(o);
return a;
}
// https://stackoverflow.com/a/47506893/860099
function B(a,o) {
a[a.length] = o;
return a;
}
// https://stackoverflow.com/a/6254088/860099
function C(a,o) {
return a.concat(o);
}
// https://stackoverflow.com/a/50933891/860099
function D(a,o) {
return [...a,o];
}
// https://stackoverflow.com/a/42428064/860099
function E(a,o) {
const frozenObj = Object.freeze(o);
return Object.freeze(a.concat(frozenObj));
}
// https://stackoverflow.com/a/6254088/860099
function F(a,o) {
a.unshift(o);
return a;
}
// -------
// TEST
// -------
[A,B,C,D,E,F].map(f=> {
console.log(`${f.name} ${JSON.stringify(f([1,2],{}))}`)
})
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"> </script>
This shippet only presents functions used in performance tests - it not perform tests itself!
And here are example results for chrome
You are running into a scope problem if you use your code as such. You have to declare it outside the functions if you plan to use it between them (or if calling, pass it as a parameter).
var a = new Array();
var b = new Object();
function first() {
a.push(b);
// Alternatively, a[a.length] = b
// both methods work fine
}
function second() {
var c = a[0];
}
// code
first();
// more code
second();
// even more code

Categories

Resources