I ran console.log(object). This is what is shown in the console:
How can I access any of this information? For example the info in $oel
Like many languages, JavaScript syntax uses "dot notation" to access properties on objects:
object.$oel
Those properties may be primitive values:
console.log(object.$oel)
or perhaps objects with their own properties:
console.log(object.$oel.someProperty)
or perhaps functions:
object.$oel()
Regardless of the type, the syntax to reach it is the same.
You can you standard dot notation to access object attributes, eg:
object.attr;
Regards.
Related
I am using this script to make a style object of all the inherited, etc. styles.
var style = css($(this));
alert (style.width);
alert (style.text-align);
With the following, the first alert will work fine, but the second one doesn't... it's interpreting the - as a minus I assume. The debugger says 'uncaught reference error'. I can't put quotes around it, though, because it isn't a string. So how do I use this object property?
Look at the comments. You will see that for CSS properties, the key notation is not compatible with a number of properties. Using the camel case key notation therefore is the current way:
obj.style-attr // would become
obj["styleAttr"]
Use key notation rather than dot
style["text-align"]
All arrays in JavaScript are objects and all objects are just associative arrays. This means you can refer to a place in an object just as you would refer to a key in an array.
arr[0]
or the object
obj["method"] == obj.method
A couple things to remember when accessing properties this way:
they are evaluated so use strings unless you are doing something with a counter or using dynamic method names.
This means obj[method] would give you an undefined error while obj["method"] would not
You must use this notation if you are using characters that are not allowed in JavaScript variables.
This regex pretty much sums it up:
[a-zA-Z_$][0-9a-zA-Z_$]*
The answer to the original question is: place the property name in quotes and use array style indexing:
obj['property-with-hyphens'];
Several have pointed out that the property you are interested in is a CSS property. CSS properties that have hyphens are automatically converted to camel casing. In that case you must use the camel cased name like:
style.textAlign;
However this solution only works for CSS properties. For example,
obj['a-b'] = 2;
alert(obj.aB); // undefined
alert(obj['a-b']); // 2
CSS properties with a - are represented in camelCase in JavaScript objects. That would be:
alert( style.textAlign );
You could also use a bracket notation to use the string:
alert( style['text-align'] );
Property names may only contain characters, numbers, the well known $ sign and the _ (thanks to pimvdb).
Use brackets:
var notTheFlippingStyleObject = {
'a-b': 1
};
console.log(notTheFlippingStyleObject["a-b"] === 1); // true
More information on objects: MDN
NOTE: If you are accessing the style object, CSSStyleDeclaration, you must use camelCase to access it from JavaScript. More information is here.
alert(style.textAlign)
or
alert(style["textAlign"]);
To directly answer the question: style['text-align'] is how you would reference a property with a hyphen in it. But style.textAlign (or style['textAlign']) is what should be used in this case.
Hyphenated style properties are referenced via camelCase in JavaScript, so use style.textAlign.
To solve your problem: The CSS properties with hyphens in them are represented by JavaScript properties in camelCase to avoid this problem. You want: style.textAlign.
To answer the question: Use square bracket notation: obj.prop is the same as obj["prop"] so you can access property names using strings and use characters that are forbidden in identifiers.
I think in the case of CSS styles they get changed to camelCase in JavaScript, so test-align becomes textAlign.
In the general case, where you want to access a property that contains non-standard characters, you use array-style: ['text-align']
The object property names are not one-to-one matches for the CSS names.
At first, I wondered why the solution didn't work on my end:
api['data-sitekey'] // Returns undefined
...later on I figured out that accessing data attributes was different:
It should be like this:
var api = document.getElementById("some-api");
api.dataset.sitekey
Incoming "noob" question:
Javascript has an includes method on arrays.
It looks like:
Array.includes()
But when I go to the Javascript Manual to understand this method, the heading on that page (for an appropriate technical reason, I realize) is:
Array.prototype.includes()
Similar things in the Javascript Manual have caused me to not like the manual at all (and alas, I rely on W3Schools more than the manual).
However, I really really want to learn to interpret the manual.
So, my question is: what's the significance of including the word .prototype in Array.prototype.includes() in the documentation, when the actual usage looks like: Array.includes()?
(Also, if anyone has suggestions on how I can improve my comprehension of the official Javascript Manual, I'd appreciate suggestions.)
So, my question is: what's the significance of including the word .prototype in Array.prototype.includes() in the documentation, when the actual usage looks like: Array.includes()?
The significance is that actual usage doesn't look like Array.includes():
Array.includes();
That will throw a TypeError: Array.includes is not a function because Array.includes doesn't exist. Accessing a non-existing property evaluates to undefined, so Array.includes evaluates to undefined and thus Array.includes() is trying to call undefined as if were a function.
You can see that in action here:
console.log(Array.includes);
undefined();
The includes() method is defined on the prototype of the Array global object so that you can call it on instances of Array:
[].includes();
You can see that [].includes is a function:
console.log([].includes);
Compare this to Array.from which is defined on the Array constructor, not on the Array prototype:
console.log(Array.from);
You can use it like this:
console.log(Array.from({ length: 10 }, (_, num) => num << 2));
If the documentation said Array.includes() you would literally type it like this (example):
Array.includes(1);
Instead it says Array.prototype.includes() which means it isn't called on the Array type itself, but on an instance of it. So in this case you would write:
const numbers = [1, 2, 3];
numbers.includes(1);
JavaScript is often described as prototype-based language, prototypes is simply how inheritance works in JavaScript.
What does prototype means ?
Both of us agree that almost everything in JavaScript is an object (I said "Almost" because primitives are not considered objects) cool?
Okay, now every Object in JS has an internal property called [[Prototype]] and by internal I mean that you can't access it directly the same way you access a JS object's property.
If we want to know the prototype of an object that we have created we either pass the instance of our object to Object.getPrototypeOf or through the __proto__ property of our object
For example:
let myArray = [1,2,3,4];
console.log(myArray.__proto__)
// Expected output: Array []
If you expand the resulting object you get from the little code snippet above you will find the includes method you were asking about and all of the methods available on any array you create in a JS code!
That's because myArray and all arrays in JavaScript are said to share the properties and methods defined on Array.prototype!
Now, if you look again at the methods of the resulting object which you have from the code snippet above you will notice a method called constructor, defined on the Array.prototype just like includes and the other methods
That's the function invoked when you create an instance of the JavaScript Array object!
What do we mean by the JavaScript Array object?
It's a global JavaScript object that is used in the construction of arrays, it's the Array in Array.prototype.includes() (you may call it a class for convenience buuuuut classes did not exist practically until the release of ES6...before then there was no such thing as class in JS)
So to keep it simple and wrap it up think of Array as the global object that alll JS arrays are instances of, and think of Array.proto as it's prototype which wraps the properties and methods that all of its instances share!
And regarding the documentation, being able to read the documentation and have a considerable understanding of what you read is actually something good so I believe you're just fine !
I am using this script to make a style object of all the inherited, etc. styles.
var style = css($(this));
alert (style.width);
alert (style.text-align);
With the following, the first alert will work fine, but the second one doesn't... it's interpreting the - as a minus I assume. The debugger says 'uncaught reference error'. I can't put quotes around it, though, because it isn't a string. So how do I use this object property?
Look at the comments. You will see that for CSS properties, the key notation is not compatible with a number of properties. Using the camel case key notation therefore is the current way:
obj.style-attr // would become
obj["styleAttr"]
Use key notation rather than dot
style["text-align"]
All arrays in JavaScript are objects and all objects are just associative arrays. This means you can refer to a place in an object just as you would refer to a key in an array.
arr[0]
or the object
obj["method"] == obj.method
A couple things to remember when accessing properties this way:
they are evaluated so use strings unless you are doing something with a counter or using dynamic method names.
This means obj[method] would give you an undefined error while obj["method"] would not
You must use this notation if you are using characters that are not allowed in JavaScript variables.
This regex pretty much sums it up:
[a-zA-Z_$][0-9a-zA-Z_$]*
The answer to the original question is: place the property name in quotes and use array style indexing:
obj['property-with-hyphens'];
Several have pointed out that the property you are interested in is a CSS property. CSS properties that have hyphens are automatically converted to camel casing. In that case you must use the camel cased name like:
style.textAlign;
However this solution only works for CSS properties. For example,
obj['a-b'] = 2;
alert(obj.aB); // undefined
alert(obj['a-b']); // 2
CSS properties with a - are represented in camelCase in JavaScript objects. That would be:
alert( style.textAlign );
You could also use a bracket notation to use the string:
alert( style['text-align'] );
Property names may only contain characters, numbers, the well known $ sign and the _ (thanks to pimvdb).
Use brackets:
var notTheFlippingStyleObject = {
'a-b': 1
};
console.log(notTheFlippingStyleObject["a-b"] === 1); // true
More information on objects: MDN
NOTE: If you are accessing the style object, CSSStyleDeclaration, you must use camelCase to access it from JavaScript. More information is here.
alert(style.textAlign)
or
alert(style["textAlign"]);
To directly answer the question: style['text-align'] is how you would reference a property with a hyphen in it. But style.textAlign (or style['textAlign']) is what should be used in this case.
Hyphenated style properties are referenced via camelCase in JavaScript, so use style.textAlign.
To solve your problem: The CSS properties with hyphens in them are represented by JavaScript properties in camelCase to avoid this problem. You want: style.textAlign.
To answer the question: Use square bracket notation: obj.prop is the same as obj["prop"] so you can access property names using strings and use characters that are forbidden in identifiers.
I think in the case of CSS styles they get changed to camelCase in JavaScript, so test-align becomes textAlign.
In the general case, where you want to access a property that contains non-standard characters, you use array-style: ['text-align']
The object property names are not one-to-one matches for the CSS names.
At first, I wondered why the solution didn't work on my end:
api['data-sitekey'] // Returns undefined
...later on I figured out that accessing data attributes was different:
It should be like this:
var api = document.getElementById("some-api");
api.dataset.sitekey
I am trying to use an element class name and call it as a method for my object.
var thisClass=$this.attr('class')
//thisClass = 'call'
obj.thisClass(ID);
My codes don't work as I wanted to be. Are there anyways to solve this? Thanks a lot!
You can do
obj[methodName](arguments, ...);
This works because functions are objects as well in javascript and are themselves only attributes of their objects. Object properties can be accessed with the . and the [] notation whereas the [] notations is needed for dynamic names or names that are not legal javascript identifiers.
What does this mean?
var settings = {
"column-1" : ["block-1"],
"column-2" : ["block-2"]
};
It means one should [likely] read a tutorial/book on JavaScript before asking questions like this on SO ;-) (Explaining what "it means" will likely have not much "practical meaning" by itself.)
Like Eloquent JavaScript: A Modern Introduction to Programming
I believe the exact construct/term that is being sought is "object literals" -- {...} is for objects and [...] is for arrays.
Happy coding.
This will create a new object and store it in the settings variable.
The object is created by an Object literal and consist out of two propertys (column-1 and column-2) which are both assigned an Array with a single String value.
It defines an object containing two properties (column-1 and column-2) which both contain arrays which both contain a single value (block-1 an block-2).
Due to the - in the property name it will be impossible to access them using the object.property syntax so you'll have to use the array syntax: object['property']
Initialized a variable named settings and assigned the value {"column-1": ["block"], "column-2": ["block-2"]}, which is an object, to the settings.