I am a total newbie and ignoramus when it comes to JavaScript. Unlike other computer languages I have encountered, Javascript has these complex nested variables. Is it possible to construct variables such as this?
For example in,
var verycomplexstruct: {
this: "some value", {
that: [123,45,67,78,89,123], {
etc
can I have this type of definition,
var abc = "123";
var myData = [123,45,67,78,89,123];
var verycomplexstruct: {
this: abc, {
that: mydata, {
etc
Not surprisingly, it does not seem to work. The use case is in charts.js where the chart data variable structure is very tricky and error prone, but where the same chart is reused all the time with only the updated label and data set(s) changing. Having separate variables for the data that is frequently updated seems like a sensible idea to me. But how to achieve this in Javascript?
答案 0 :(得分:1)
Your syntax won't work in your first example in a couple places. There are some great tutorials out there. Most of your issues above come from the fact that you're not assigning everything in your object to a key.
For example, you have a pattern of
var myObject = {
thing1: 'thing one',
{
thing2: 'thing two',
}, // etc
}
After the first comma, on the same line as 'thing one'
, you start another object. You need to assign that object to a key in the parent object.
var myObject = {
thing1: 'thing one',
secondObject: {
thing2: 'thing two',
}, // etc
}
But like I said, there are tons of resources out there for beginner JS. I'd start there before posting to SO.
答案 1 :(得分:0)
Yes. The right-hand side of a name: property
pair in an object literal just needs to be an expression.
Your problems are caused by typos, not by the use of variables.
myData
and mydata
are different variable names=
, not :
property: value
separated by commas. You forgot the property:
part sometimes and just had a value.var abc = "123";
var myData = [123, 45, 67, 78, 89, 123];
var verycomplexstruct = {
this: abc,
something: {
that: myData,
something_else: {}
}
};
console.log(verycomplexstruct);