Putting items in JavaScript arrays on arbitrary indices [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Are Javascript arrays sparse?
Is the following "safe" in JavaScript? (as in, can be expected to work reliably on all JavaScript engines)
a = [];
a[100] = "hello";
a[100] == "hello"; // should be true

Yes. Arrays in JavaScript are sparse and your code is expected to work in all JavaScript implementations.
You can get into requirements in the section 15.4 of the specification(PDF).
Short summary: array is special object that have length property adjusted when one adds elements at properties with numeric names (like `a[123]="test"). Other methods like join take length into account duuring operations.

Yes, why wouldn't it work? Its perfectly acceptable syntax.

You can even assume
a[100] === "hello"; // will return true

Related

Why can we use the .length property in string types? [duplicate]

This question already has answers here:
How does primitive types in Javascript have methods and Properties? [duplicate]
(2 answers)
Closed last year.
Hello I'm new to JS and object-oriented programming in general.
I have two questions considering this
let arr = [1,2,3]
let a = 'hi'
When I run typeof(), arr is 'object' and a is 'string' right?
So my question is ,
When using arr.length to get the length of the array, what's the principle behind it? To be specific, I don't understand how I could get the length property though I've never initialized it. Does JS automatically set a length property value when we generate an object? How does it work?
Doesn't property only exist in objects? But why can we get the length of variable a using a.length? I thought objectname.property thing was for objects.
When you declare [1,2,...] you are declaring an object of class Array, which, in it's prototype, has a "length" property. Think of it as a variable that gets updated when you add or remove elements from the array.
https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/length
Strings are also objects in Javascript, and a string is also considered an array of characters, thus having the "length" property as well.
https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String

Any way in JavaScript to deep-check an object for a truthy value? [duplicate]

This question already has answers here:
Null-safe property access (and conditional assignment) in ES6/2015
(11 answers)
Closed 6 years ago.
I believe there's a mechanism for this in CoffeeScript (the ? token), but I'm wondering if there's a better way to do this kind of check in ES6:
if (item && item.integrations && item.integrations.slackData) ...
(besides writing a helper function, which is the immediately obvious solution)
EDIT: The goal here is to make the code is simple and terse as possible.
Example object:
item = { integrations: { slackData: { url: '...' } } };
EDIT 2: Thanks for pointing out the duplicates. I couldn't figure out what terms to search for. I'm probably going to go with using lodash's _.get() function.
You can use Array.prototype.every()
var check = [item, item.integrations, item.integrations.slackData]
.every(function(element) { return element });
Edit, Updated
As noted at comments by #FelixKling, the pattern at above using .every() will fail if item.integrations is undefined.
Given the example object at Question you can use JSON.stringify(), String.prototype.match() with RegExp /"integrations":|"slackData":|"ur‌​l":/g/, then check that .length of resulting array, if any, is equal to the number of properties expected; in the present case 3.
A javascript object which is passed to JSON.stringify() should have properties with the following pattern:
" followed by property followed by " followed by :. Depending on the source object, the RegExp can be further adjusted to meet the specific properties and values of that object.
JSON.stringify(item).match(/"integrations":|"slackData":|"ur‌​l":/g).length === 3
Note that JSON.stringify() has a replacer option which can be used to match properties of the object. The replacer function option is recursive. See also
remove object from nested array
Nested object and array destructuring
Convert javascript object to array of individual objects
How do I filter Object and get a new Object?
but I'm wondering if there's a better way to do this kind of check in
ES6:
The present Answer does not attempt to indicate that using JSON.stringify() and RegExp to match or filter a javascript object is "better"; but only that the approach can meet the described requirement at the present Question.

JavaScript for..in statement give unexpected results in IE8 [duplicate]

This question already has answers here:
Elements order in a "for (… in …)" loop
(10 answers)
Sort JavaScript object by key
(37 answers)
Closed 8 years ago.
I have an object which would translate into a Dictionary in C# and I'm trying to loop through all my "keys" so that I can draw my objects in order.
Let's say that this dictionary contains three objects with the keys 1, 2 and 3.
for (var key in myDictionary) {
if (key === "indexOf" || key === "length")
continue;
// Do stuff...
}
Now, in IE9+, Chrome and Firefox, the output will be 1, 2, 3 while in IE8 the output is 2, 1, 3.
As it is crucial for my application that these objects are given in order you can understand that this is unwanted behavior.
My question, therefore, is:
Why does this happen and is there a known workaround that fixes my issue?
That happens because the properties in an object doesn't have any specific order. The order that you get the propeties is depending on the implementation, i.e. how the properties are stored internally in the object.
The browsers that return the properties in a different order than you expect aren't doing anything wrong, the actual error is to expect any specific order.
If you want the properties in a specific order, you need to sort them. You can put them in an array, sort the array, and loop through the array.

Javascript. Swap two variables. How it works? [duplicate]

This question already has answers here:
javascript variable swapping using arrays
(3 answers)
Closed 8 years ago.
Saw in a single source next:
[param_o,param_got] = [param_got,param_o];
This code swap variables param_o & param_got.But how [param_o,param_got] = [param_got,param_o] works, if [] is new instance of Array in Javascript ?
EDIT
Try checking:
var param_o = 1;
var param_got = 2;
[param_o,param_got] = [param_got,param_o];
console.log(param_o+" "+param_got);
// 2 1
This notation is called destructuring assignment and is part of Javascript 1.7:
Destructuring assignment makes it possible to extract data from arrays
or objects using a syntax that mirrors the construction of array and
object literals.
The object and array literal expressions provide an easy way to create
ad-hoc packages of data. Once you've created these packages of data,
you can use them any way you want to. You can even return them from
functions.
One particularly useful thing you can do with destructuring assignment
is to read an entire structure in a single statement.
The first sample actually demonstrates explicitly that this is useful to avoid temporary variables as in your code sample.
Firefox has supported this feature since Firefox 2 already. For Chrome the bug is still open after 3 years. IE11 doesn't support it either from what I've just tested.

For loop in array reads 'remove'? [duplicate]

This question already has answers here:
Problems with JavaScript "for in" loop
(3 answers)
Closed 9 years ago.
I just experienced the strangest thing, this is the code I'm actually using :
for (iter in data.List) {
console.log(iter);
}
As you would expect, the log should give the number of each row (0, 1, 2...), instead it gives me this :
0
1
2
remove
Knowing that my array only has 3 rows
Did anybody ever encountred this ?
Basically, the problem is that you are iterating through your array using a for in loop, which is not meant for iteratung through arrays. Its intent is to iterate through all properties of an object, and apparently there is a property called remove on your array.
For more details on why for in is a bad idea when it comes to arrays, see Why is using "for...in" with array iteration a bad idea?.
As solution, I'd suggest to use an indexed for loop. This type of loop does not care about properties, hence you are fine. So it basically comes down to a very classical:
for (var i = 0; i < data.List; i++) {
console.log(data.List[i]);
}
By the way: You should not uppercase anything in JavaScript, unless it's a constructor function. Hence it should be data.list.
PS: A nice read when it comes to arrays and (mis-)using them, read Fun with JavaScript Arrays, a quite good read.
Yes, that is how for..in works in JavaScript. It enumerates over all object properties (not Array indexes). Simple solution: don't use for..in on Arrays, because that's not what it is for.

Categories

Resources