I am trying to get load a variable from a array variable for my project but the value comes back as undefined I just used the console.log for the test output.
I want to learn how to use it after seeing others use on their projects and I want to do it to make my projects easier to manage.
I set it to trigger when the page loads up first thing.
Any help is welcome from the community.
My code if it helps solve it problem:
window.addEventListener('load',function(){
var values = [
odds_base = 10,
start_cash = 50
]
console.log(values.odds_base)
});
In this case I think you have to use an object like this one, instead of array:
window.addEventListener('load',function() {
var values = {
odds_base: 10,
start_cash: 50
};
console.log(values.odds_base);
});
You are using the wrong data structure here. Square brackets are used for arrays. You should use a javascript object here.
window.addEventListener('load',function(){
var values = {
odds_base: 10,
start_cash: 50
}
console.log(values.odds_base)
});
Or you can do like this
let values = {};
values.odds_base = 10;
values.start_cash = 50;
console.log(values.odds_base);
If that is array then you have to use variables like this
window.addEventListener('load',function(){
var values = [
odds_base = 10,
start_cash = 50
]
console.log(values);
console.log(odds_base);
console.log(start_cash);
});
When you assign array like this then Internally JavaScript first Creates the variable and then assign those variables in array
Otherwise convert that array to object and do like as follows
window.addEventListener('load',function(){
var values = {
odds_base : 10,
start_cash : 50
}
console.log(values);
console.log(values.odds_base);
console.log(values.start_cash);
});
The value of values looks like it should be an object and not an array as seen in your example i.e. values = [ a = 1, b = 2 ] should be values = { a: 1, b: 2 }
window.addEventListener('load', function(){
var values = {
odds_base: 10,
start_cash: 50
}
console.log(values.odds_base)
});
Tip: Declare the values variable outside the scope of the addEventListener callback if you wish it to be accessible outside also.
Related
[{…}]
0: {productName: "Powermax 125", travelSpeed: 30, materialThickness: 1, process: "125 Amps"}
length: 1
__proto__: Array(0)
Hello, This is my console output from sorting 18 sets of information like this. I have successfully sorted the list to just the entry above. now I want to store each set of information into its own variable. This is in Javascript
The Variable above is sortedList
Can someone help me make code to pull each bit of information out as a new variable?
I tried
finalProduct = sortedList.productName
finalTravelSpeed = sortedlist.travelSpeed
finalMaterialThickness= sortedList.materialThickness
finalProcess = sortedlist.process
You only make some little typos: you wrote in some cases sortedlist instead of sortedList, you didn't use camelCase-writing and you forgot the ";" and the line-end.
Because your sorted list is an array and you want the first element of it you allways have to take the first element sortedList[0] and not sortedList.
let sortedList= [{productName: "Powermax 125", travelSpeed: 30, materialThickness: 1, process: "125 Amps"}];
finalProduct = sortedList[0].productName;
finalTravelSpeed = sortedList[0].travelSpeed;
finalMaterialThickness= sortedList[0].materialThickness;
finalProcess = sortedList[0].process;
console.log (finalProduct, finalTravelSpeed, finalMaterialThickness, finalProcess);
From what i understood this is an array of objects of length 1, so first you should access index 0 of that array to get that object:
let finalProduct = sortedList[0].productName
let finalTravelSpeed = sortedlist[0].travelSpeed
let finalMaterialThickness= sortedList[0].materialThickness
let finalProcess = sortedlist[0].process
as far as i understood ! you want method to pulling
data from arrays or objects and put this data in dynamic variables have same name
var sortedList= [{productName: "Powermax 125", travelSpeed: 30, materialThickness: 1, process: "125 Amps"}];
// this function for extract objects to variables worked dynamically
function extractor_Object(obj = {}){
for(let i in obj) window[i] = obj[i];
}
extractor_Object(sortedList[0]);
console.log(productName , travelSpeed , materialThickness , process);
i hope this function help you
I am trying to do the following, where foo is a function which fills the 'out' array.
But for each data centre in data centres object, pushed out array is getting overwritten by a new value.
I want to prevent this overwriting.
How to create a new array reference/ instance in a loop?
_.map(datacenters, function(datacenter){
var out = []
foo(datacenter, out);
$scope.dcSelected.push(out);
});
Put your out declaration outside:
var out = [];
_.map(datacenters, function(datacenter){
foo(datacenter, out);
$scope.dcSelected.push(out);
});
I don't fully understand what you trying to do, so I will do a general example:
var datacenters = [1,2,3,4]
var out = []
datacenters.map(function(datacenter){
datacenter2 = datacenter + 1;
out.push(datacenter2);
});
console.log(out);
[ 2, 3, 4, 5 ]
(I used map that way because I haven't imported the underscore for js)
You may try angular.copy(out) of angularJs. Hope it ll work for you
_.map(datacenters, function(datacenter){
var out = []
foo(datacenter, out);
$scope.dcSelected.push(angular.copy(out));
});
You have 2 options:
1) create a closure
2) create another array as part of your controller, that will store linkage of data center and out an array, imagine it as a key, value but in a global variable of the same controller.
Hi there before I start I did try looking through the search about writing variables so if this has been asked and answered then I do apologise but this is baffling me ....
So here goes ..
example of what I am talking about
var i = e[ab]
var n = e[cd][ef]
var t = e[cd][gh]
I know that when I want var i I can put e.ab but how would I go about writing var n and var t
So assuming your object looks like this (based on your description, it sounds like you want to access an object which is the property of another object), and you want to access them through the indexer properties (which would be a property of a property).
var e = {
ab : "variableOne",
cd : {ef:"ef object"},
gh : {ij:"ij object"},
}
var i = e["ab"]
//if these are properties, then you need to add quotes around them
//to access a property through the indexer, you need a string.
var n = e["cd"]["ef"]
var t = e["gh"]["ij"]
console.log(i);
console.log(n);
console.log(t);
console.log("this does the same thing:")
console.log(e.ab);
console.log(e.cd.ef);
console.log(e.gh.if);
In your example the object would look like
//e is the parameter, but I show it as a variable to show
// it's relation to the object in this example.
e = {
now_playing: {artist:"Bob Seger"; track:"Turn the Page"}}
}
this is different than an array of arrays:
var arr = [
['foo','charlie'],
['yip', 'steve'],
['what', 'bob', 'jane'],
];
console.log(arr[0][0]); //foo
console.log(arr[0][1]); //charlie
console.log(arr[1][0]); //yip
console.log(arr[1][1]); //steve
console.log(arr[2][2]); //jane
https://jsfiddle.net/joo9wfxt/2/
EDIT:
Based on the JSON provided, it looks like parameter e in the function is assigned the value of the item in the array. With your code:
this line will display: "Rock you like a hurricane - Nontas Tzivenis"
$(".song_title .current_show span").html(e.title);
and this line will display: "Rascal Flatts - Life is a Highway".
$(".song_title .current_song span").html(e.np);
If it's not displaying you might want to double check your JQuery selectors. This ".song_title .current_song span" is selecting it by the classes on the element.
I think you are in need of a bit of a refresher on basic JavaScript syntax. Here's how you can assign an "empty object" to a variable, then start to assign values to it's properties:
e = {}
e.ab = {}
e.cd = {}
e.cd.ef = "data"
or you can use the associative array syntax for property access:
e = {}
e["ab"] = {}
e["cd"] = {}
e["cd"]["ef"] = "data"
You see the latter is using the object e like a two-deep associative array. Is that what you are looking to do?
JavaScript is not strongly typed. So an Array "a" could contain objects of different types inside.
var a = [ "a value", [1, 2, 3], function(){ return 5 + 2;}];
var result = a[0]; //get the first item in my array: "a value"
var resultOfIndexedProperty = a[1][0]; //Get the first item of the second item: 1
var resultOfFunc = a[2](); //store the result of the function that is the third item of my array: 7
Hope this helps a little.
How would I access ArrayObjectVariable inside
ArrayObject[0]? I know if you don't have a [ ] around it its as simple
as ArrayObject[0].ArrayObjectVariable?
var ArrayObjectVariableValue = 'AyOhVeeVee';
var ArrayObject = []
ArrayObject[0] = [{ ArrayObjectVariable : ArrayObjectVariableValue }];
alert(ArrayObject[0]???);
I didn't realize the whole "ArrayObject[0][0].ArrayObjectVariable" thing. Thanks for the replies. I was trying it with just one ("[0]") instead of two ("[0][0]"). My second question is, what is the second "[0]" for? I just tried making multiple variables and it still used "[0][0]" ? So what's the second "[0]" controlling?
Third question? I noticed that it created a variable outside the array when I did that? When I change the value of the variable in the array, it has no effect on the one outside of it? Likewise, when I change the value of the variable outside of the array it has no effect on the one inside it. Is there a way to create the array without creating a variable outside of the array with the same name? Thanks :)
OK figured it out :) Just make the Object in the array without the "[ ]". The whole point of this was to figure out how to access nested items but I got it now. Didn't realize how to make them without the "[ ]". Example for those of you struggling like I was:
// create variables that we are going to use in Array Objects. Or make a function with the values.
var ATV1 = 'AyTeeVeeOne', ATV2 = 'AyTeeVeeTwo', ANV1 = 'AyEnVeeOne';
var ATV3 = 'AyTeeVeeThree', ATV4 = 'AyTeeVeeFour', ANV2 = 'AyEnVeeTwo';
// Make an Array
var ArrayObject;
ArrayObject = [{}];
// Insert variables into Array object(s).
ArrayObject[0] = {ArrayTestObject1 : { ArrayTestValue1:ATV1,
ArrayNestedObject1:{ ArrayNestedValue1:ANV1 },
ArrayTestValue2:ATV2
}};
ArrayObject[1] = {ArrayTestObject2 : { ArrayTestValue3:ATV3,
ArrayNestedObject2:{ ArrayNestedValue2:ANV2 },
ArrayTestValue4:ATV4
}};
// Access Array Object Variables
alert(ArrayObject[0].ArrayTestObject1.ArrayTestValue1) // Example 1
alert(ArrayObject[1].ArrayTestObject2.ArrayNestedObject2.ArrayNestedValue2) // Example 2
ArrayObject[0][0].ArrayObjectVariable
You have an array for the value of ArrayObject[0], so treat it like any other array.
use this:here you have ArrayObject as array and you are creating index as zero to the array and in that on zeroth place ArrayObjectVariable key resides.
<script>
var ArrayObjectVariableValue = 'AyOhVeeVee';
var ArrayObject = []
ArrayObject[0] = [{
ArrayObjectVariable : ArrayObjectVariableValue }];
alert(ArrayObject[0][0].ArrayObjectVariable);
</script>
I have a map of the US with all 50 states as clickable buttons, when the user clicks a state I want to display information about that state, calling on that state's array dynamically. Below is my own weak attempt that obviously does not work.
var stateList = new Array("AK","AL","AR","AZ","CA","CO","CT","DC","DC2","DE","FL","GA","GU","HI","IA","ID",
"IL","IN","KS","KY","LA","MA","MD","ME","MH","MI","MN","MO","MS","MT","NC","ND","NE","NH","NJ","NM","NV","NY",
"OH","OK","OR","PA","PR","RI","SC","SD","TN","TX","UT","VA","VT","WA","WI","WV","WY");
function listenerForI( i ) {
document.getElementById(stateList[i])
.addEventListener('mousedown', function() {
stateSelect(stateList[i]);
}, false);
}
for (var i = 0; i < stateList.length; i++) {
listenerForI( i );
}
var HIdat = new Array(20,28,50,2) //one array for all 50 states COdat, AKdat, etc.
function stateSelect(state){
var display_data1 = state + "dat[0]";
alert(display_data1);
}
Should I use eval()? I've heard of something you can do with a global "window[]" but I don't understand how that would work.
You should store the state arrays in their own object:
var stateData = {
HI: [1, 2, 3],
IL: [4, 5, 6],
...
};
var myData = stateData[state];
Using window is an option, like this:
window[state + "dat"] will get you the array.
But I would suggest ... exactly what SLaks just posted, so do that instead.
In JavaScript, global vars are members of the window object, so you can use the array indexing syntax to get at them without using eval, which is generally to be avoided, like so:
function stateSelect(state) {
var display_data1 = window[state + "dat"];
alert(display_data1);
}