What does this mean in var definition:
var array = array || [];
... and next two parts of javascript are equal each other?
var array = array || [];
array.push([1],[2]);
array.push([3]);
=
var array = array.push([1],[2],[3]) || [];
?
The first statement will set array to an empty array if it is a falsey value (null, undefined, etc.).
The next two parts are not equal, and will likely fail when you try to call push on something that is not known to be an array.
It is equivalent to this,
var array;
if(array){
array = array;
} else {
array = [];
}
Just in a much shorter form.
In the second part, No those two are not equivalent.
array.push([1],[2],[3])
needs to be executed no matter what, if you use || [] it will not be added.
In other words, you start with this,
var array;
if(array){
array = array;
} else {
array = [];
}
array.push([1],[2],[3]);
And you then modified it to this,
var array;
if(array){
array = array;
array.push([1],[2],[3]);
} else {
array = [];
}
It means that if array is a falsy value (undefined, null etc.) - the value that will be assigned to the var array is an empty array - [];
EDIT:
the second part of your question - no these are not equivalent.
For instance, when array is undefined:
var array = array.push([1],[2],[3]) || [];
this will throw an exception.
This:
var array = array || [];
array.push([1],[2]);
array.push([3]);
will not.
It's setting the var to a new array if it's not defined.
That syntax uses the javascript boolean or operator, and its evaluation of truthy/falsey statements to provide a valid default value.
So
var array = array || [];
Means "use an empty array if array evaluates false".
Related
I have this Json data I get from server in javascript
var mydata = JSON.parse('["X","Y","Z"]');
Below I have the following data model in javascript..
var mySchemasList = {
schemas: [new SelectSchemaModel("A", false),
new SelectSchemaModel("B", false),
new SelectSchemaModel("C", false)
]
};
I want to create this model dynamically by getting data ('A','B','C') from mydata..
Any help is sincerely appreciated..
Thanks
Can't you just do something like the following?
var i
var mySchemaList = {schemas:[]};
for (i = 0; i < mydata.length; i++) {
mySchemaList.schemas.push( new SelectSchemaModel(mydata[i], false) );
}
In javascript, objects and arrays are accessed using the . or [] operators. The following two lines does exactly the same thing:
mySchemasList.schemas;
mySchemasList['schemas'];
Also, each member of an object or array act like a variable on its own. So you can assign values, objects or arrays to them:
mySchemasList = {};
When a variable (or property) is declared but not assigned anything its value is undefined. So you can check simply by:
if (mySchemasList === undefined) mySchemasList = {};
Alternatively you can use || short circuiting since undefined is considered false:
mySchemasList = mySchemasList || {};
putting this all together, the following two examples does exactly the same thing.
Example 1:
var mySchemasList = {
schemas : []
}
Example 2:
var mySchemasList = {};
mySchemasList.schemas = [];
Now that you've created an array at mySchemasList.schemas you can start pushing other objects into it:
mySchemasList.schemas.push(new SelectSchemaModel("A", false));
mySchemasList.schemas.push(new SelectSchemaModel("B", false));
mySchemasList.schemas.push(new SelectSchemaModel("C", false));
Wrapping it up in a for loop parsing the JSON data, you'd do this:
var mydata = JSON.parse(ajax.responseText);
for (var i=0; i<mydata.length; i++) {
mySchemasList.schemas.push(new SelectSchemaModel(mydata[i],false));
}
Is there a way for this line to always work and not throw TypeError: Cannot read property 'Whatever' of undefined
var MyArray = [];
MyArray[StringVariableName][StringVariableName2].push("whatever");
Try this:
var MyArray = [];
MyArray[StringVariableName] = MyArray[StringVariableName] || [];
MyArray[StringVariableName][StringVariableName2] = MyArray[StringVariableName][StringVariableName2] || [];
MyArray[StringVariableName][StringVariableName2].push("whatever");
You could even, through the power of expressions, do this with a one-liner.
(MyArray[StringVariableName][StringVariableName2] || (MyArray[StringVariableName][StringVariableName2] = [])).push("whatever");
You could use the literal syntax to set things up like you'd have them:
var myObj = {
StringVariableName: {
StringVariableName2: []
}
};
myObj.StringVariableName.StringVariableName2.push("whatever");
I think instead of using array in the first place, use object if your keys are not integers.
In Javascript Arrays are also object So it is not wrong to do this
var a = [];
a['key'] = 'something';
console.log(a); //Gives []
I think it is conceptually wrong So instead of using Array to hold such pair of data you should use objects. See this:
var myObject = myObject || {};
myObject[str1] = myObject[str1] || {};
myObject[str1][str2] = myObject[str][str2] || [];
// Now myObject[str1][str2] is an array. Do your original operation
myObject[str1][str2].push("whatever");
To check without getting an error:
this snippet allows you to check if a chained object exists.
var x;
try{x=MyArray[name1][name2][name3][name4]}catch(e){}
!x||(x.push('whatever'));
from
https://stackoverflow.com/a/21353032/2450730
Shorthand creation of object chains in Javascript
this function allows you to create chained objects with a simple string.
function def(a,b,c,d){
c=b.split('.');
d=c.shift();//add *1 for arrays
a[d]||(a[d]={});//[] for arrays
!(c.length>0)||def(a[d],c.join('.'));
}
usage
var MyArray={};//[]
def(MyArray,'name1.name2.name3.name4');//name1+'.'+name2....
from
https://stackoverflow.com/a/21384869/2450730
both work also for arrays with a simple change.replace {} with []
if you have any questions just ask.
I am trying to make a two dimensional array out of two one dimentional arrays with this code:
var PassAssoArr = new Array();
for(k in PassPourcentNames) {
PassAssoArr[k][0] = PassPourcentNames[k]
PassAssoArr[k][1] = PassPourcentValue[k]
}
However, I get the error message: " 'undefined' is null or not an object " and it points to the first line after the for statement.
PassPourcentNames and PassPourcentValue have the same number of elements and none of the values are null. The first one contain strings and the second one integers.
Any help is greatly apreciated.
var PassAssoArr = new Array();
for(k in PassPourcentNames) {
PassAssoArr[k] = new Array();
PassAssoArr[k][0] = PassPourcentNames[k]
PassAssoArr[k][1] = PassPourcentValue[k]
}
Also instead of new Array() you can use []
var PassAssoArr = [];
for(k in PassPourcentNames) {
PassAssoArr[k] = [];
PassAssoArr[k][0] = PassPourcentNames[k]
PassAssoArr[k][1] = PassPourcentValue[k]
}
I believe this is actually faster in most JS engines.
First define PassAssoArr[k] = []; before assigning to [0] and [1].
Javascript does not support true multi-dimensional arrays.
You're trying to use nested arrays without creating the inner arrays.
You need to put an array into each element of the outer PassAssoArr:
PassAssoArr[index] = []; //Empty array literal
You're only defining one dimension of PassAssoArr - you need to set PassAssoArr[k] = new Array();
Try just doing:
PassAssoArr[k] = new Array(PassPourcentNames[k], PassPourcentValue[k]);
My problem with this is that the loop keeps going into the if statement even for duplicate barcodes. I'm trying to enter the if statement only for unique barcodes but at the end of the loop myArray has duplicates in it....why?
var myArray = new Array(); var i = 0;
$("li.foo").each(function(){
var iBarCode = $(this).attr('barcode');
if( !( iBarCode in myArray ) ){
myArray[i++] = iBarCode;
//do something else
}
});
Jquery has an inArray() function.
var myArray = new Array(); var i = 0;
$("li.foo").each(function(){
var iBarCode = $(this).attr('barcode');
if( $.inArray(iBarCode, myArray) == -1 ){
myArray[i++] = iBarCode;
//do something else
}
});
The in keyword search for properties, for instance when you want to know if an object has some method available. Since you are looking for values, it always returns false.
You should instead use an array search function as Gazler advises.
2021 Update
let myArray = [...new Set([...document.querySelectorAll('li.foo')].map(a => a.dataset.barcode))]
Working backwards: Create an array using the spread syntax from the matching elements, which Map only the data-barcode attribute. Use that to create a new Set, then create an array from that set
I have an array of objects in javascript. I use jquery.
How do i get the first element in the array? I cant use the array index - as I assign each elements index when I am adding the objects to the array. So the indexes arent 0, 1, 2 etc.
Just need to get the first element of the array?
If you don't use sequentially numbered elements, you'll have to loop through until you hit the first one:
var firstIndex = 0;
while (firstIndex < myarray.length && myarray[firstIndex] === undefined) {
firstIndex++;
}
if (firstIndex < myarray.length) {
var firstElement = myarray[firstIndex];
} else {
// no elements.
}
or some equivalently silly construction. This gets you the first item's index, which you might or might not care about it.
If this is something you need to do often, you should keep a lookaside reference to the current first valid index, so this becomes an O(1) operation instead of O(n) every time. If you're frequently needing to iterate through a truly sparse array, consider another data structure, like keeping an object alongside it that back-maps ordinal results to indexes, or something that fits your data.
The filter method works with sparse arrays.
var first = array.filter(x => true)[0];
Have you considered:
function getFirstIndex(array){
var result;
if(array instanceof Array){
for(var i in array){
result = i;
break;
}
} else {
return null;
}
return result;
}
?
And as a way to get the last element in the array:
function getLastIndex(array){
var result;
if(array instanceof Array){
result = array.push("");
array.pop;
}
} else {
return null;
}
return result;
}
Neither of these uses jquery.
Object.keys(array)[0] returns the index (in String form) of the first element in the sparse array.
var array = [];
array[2] = true;
array[5] = undefined;
var keys = Object.keys(array); // => ["2", "5"]
var first = Number(keys[0]); // => 2
var last = Number(keys[keys.length - 1]); // => 5
I was also facing a similar problem and was surprised that no one has considered the following:
var testArray = [];
testArray [1245]= 31;
testArray[2045] = 45;
for(index in testArray){
console.log(index+','+testArray[index])
}
The above will produce
1245,31
2045,45
If needed you could exist after the first iteration if all that was required but generally we need to know where in the array to begin.
This is a proposal with ES5 method with Array#some.
The code gets the first nonsparse element and the index. The iteration stops immediately with returning true in the callback:
var a = [, , 22, 33],
value,
index;
a.some(function (v, i) {
value = v;
index = i;
return true;
});
console.log(index, value);
If you find yourself needing to do manipulation of arrays a lot, you might be interested in the Underscore library. It provides utility methods for manipulating arrays, for example compact:
var yourArray = [];
yourArray[10] = "foo";
var firstValue = _.compact(yourArray)[0];
However, it does sound like you are doing something strange when you are constructing your array. Perhaps Array.push would help you out?