How to get value of key from the array in java script - javascript

I have created static array as following below
country["0"]=[USA];
sate[country[0][0]]=[["NewYork","NY"],["Ohio,"Oh"]]
for (var i = 0; i < sate[country[0][0]].length; i++) {
var key = state[country[0][0]] [i][0];
var value = state[country[0][0]] [i][i+1];
}
from above loop i am able to get the keys of state like NewYork and Ohio.
Please help me how i will get the value of "NY" and "Oh"?

var value = state[country[0][0]] [i][1];

There are a couple or three errors in your code. Assuming country has a list of countries and state keeps the states of the country...
country = ["USA"];
state = {"USA": [["NewYork","NY"],["Ohio","Oh"]] };
for (var i = 0; i < state[country[0]].length; i++) {
var key = state[country[0]] [i][0];
var value = state[country[0]] [i][1];
}

You have mistyped here
sate[country[0][0]]=[["NewYork","NY"],["Ohio", "Oh"]]
and You can get ["NY", "Oh"] by using this:
for (var i = 0; i < sate[country[0][0]].length; i++) {
var key = state[country[0][0]] [i][0];
var value = state[country[0][0]] [i][1];
}

Related

Create variable name with increment

I need to create dynamically name of variable with a loop .
example:
const1 = test;
const2 = test;
const3 = test;
....
I try this , but that only create 20 same variable name in array
I need a unique name increment by 1 at each loop and return each variable to use after.
function createVariables(){
var accounts = [];
for (var i = 0; i <= 20; ++i) {
accounts[i] = "whatever";
}
return accounts;
}
how can I do this ?
Using Object could be the work around
var accounts = {};
for (var i = 0; i <= 20; ++i) {
accounts["const"+i] = "test";
}
console.log(accounts)
If you need variable (not array), then you can use this code:
for (let i = 0; i <= 20; ++i) {
window[`whatever${i}`] = + i;
}
console.log(whatever0)
console.log(whatever1)
//...
console.log(whatever19)
See in playground: https://jsfiddle.net/denisstukalov/thvc2ew8/4/
What is it that you are trying to achieve? As mentioned in some of the comments, and array would be a better approach.
That said, one solution is to set values on a JavaScript object using string indexer (['']). See example below:
function createVariables(obj){
for (var i = 0; i <= 20; ++i) {
obj[`const${i}`] = "whatever";
}
}
// add it to a new object
const accounts = {};
createVariables(accounts);
console.log(accounts.const1, accounts.const2, accounts.const3);
// avoid adding it to global scope (like window)
createVariables(window);
console.log(const1, const2, const3);

Console.log gives correct output but when accessing set value it gives wrong output

Called Function:
this.findVerticalPossibleScoring = function(){
var possibilitySet = [];
for (var j = 0; j < 9;j++ ) {
for (var i = 0; i < 7; ){
var tempTile = this._tiles[i][j];
if(this.gameTilesValue[i][j]!=-1){
var tileTagValue = this.gameTilesValue[i][j];
if(this.gameTilesValue[i+1][j]==tileTagValue && this.gameTilesValue[i+2][j]==tileTagValue){
setElement = [];
do{
var tempPoint = this.makeArray(i,j);
setElement.push(tempPoint);
console.log(" verical i:"+i+" j:"+j);
i=i+1;
}while(i<9&&this.gameTilesValue[i][j]==tileTagValue);
possibilitySet.push(setElement);
continue;
}
}
i = i+1;
}
}
return possibilitySet;
};
this.makeArray = function (a,b){
console.log("element i:"+a+" j:"+b);
var arrayTemp = [];
arrayTemp.push(a);
arrayTemp.push(b);
return arrayTemp;
};
Calling function part:
if(scoringPossible == true){
//blast the tiles and add new tiles;
var verticalPossibleScoring = this.findVerticalPossibleScoring();
toBeDeletedTiles = [];
for(var i=0;i<verticalPossibleScoring.length;i++){
var tempSet = verticalPossibleScoring[i];
for(var j = 0;j<tempSet.length;j++){
var tempSetEntry = tempSet[i];
console.log("TILE i:"+tempSetEntry[0]+" j:"+tempSetEntry[1]);
}
}
}
I have added called function as well as calling function if loop as calling function is too big. I know this is infamous javascript loop issue. I am using gc-devkit game engine which is new and I new to it. I had solved the same issue for UIImage in it by creating custom class, but here I don't require custom array for it. Can any one guide me through this issue. Thanks in advance.
You use j as your loop variable when iterating over tempSet but then use i when getting elements from tempSet. Maybe just change
var tempSetEntry = tempSet[i];
to
var tempSetEntry = tempSet[j];

get value from variable dynamically

I'm trying, but unsuccessfully, to get the value of a variable, where the variable name is dynamic
var v_1playerName = document.getElementById("id_1playerName").value;
var v_2playerName = document.getElementById("id_2playerName").value;
for (i = 1; i <=5 i++) {
alert(window["v_"+i+"playerName"]);
}
Is this possible?
A simple thing would be to put the variables in an array and then use the for loop to show them.
var v_1playerName = document.getElementById("id_1playerName").value;
var v_2playerName = document.getElementById("id_2playerName").value;
var nameArray = [v_1playerName,v_2playerName];
for (var i = 0; i < 5; i++) {
alert(nameArray[i]);
}
Accessing variables through window isn't a great idea.
Just store the values in an object and access them using square notation:
var obj = {
v_1playerName: 0,
v_2playerName: 3
}
obj['v_' + 2 + 'playerName']; // 3
If you want to keep named references to things you could use an object.
var playerNames = {};
playerNames['p1'] = document.getElementById("id_1playerName").value;
playerNames['p2'] = document.getElementById("id_2playerName").value;
for (i = 1; i <= 2; i++) {
// dynamically get access to each value
alert.log(playerNames['p' + i])
}

Table json object in javascript

I want to make json object of html table in javascript.Currently I am able to read the each cells value in javascript, the only problem is that I am not able to retrieve as per my need so think of any suggestion here. Currently getting value like:
var x = document.getElementById("tableId");
for (var i = 0; i < x.rows.length; i++) {
for (var j = 0; j < x.rows[i].cells.length; j++){
tableJsonDTO[name] = x.rows[i].cells[j].innerHTML;
}
}
This is how i am able to read the each cell value.The table format is as follow:
header: company_1 company_2 company_3
Question1 answer_1 answer_1 answer_1
Question2 answer_2 answer_2 answer_2
and so on.How can i read the value so that i can get object like:
var obj = [{spname:"company_1",qalist:[{question:"",answer:""},{question:"",answer:""}]},{spname:"company_2",qalist:[{question:"",answer:""},{question:"",answer:""}]},{spname:"company_3",qalist:[{question:"",answer:""},{question:"",answer:""}]}]
Please give some suggestion.
You simply need to change the way you put values to tableJsonDTO. Demo.
document.getElementById('toJSON').addEventListener('click', function(){
var table = document.getElementById('mytable'),
names = [].slice.call(table.rows[0].cells),
values = [].slice.call(table.rows, 1),
out = {};
values.forEach(function(row) { //iterate over values
var cells = row.cells,
caption = cells[0].innerHTML; //get property name
[].forEach.call(cells, function(cell, idx) { //iterate over answers
var value = {},
arr;
if(!idx) return; //ignore first column
value[caption] = cell.innerHTML; //prepare value
//get or init array of values for each name
arr = out[names[idx].innerHTML] || (out[names[idx].innerHTML] = []);
arr.push(value);
});
});
console.log(out);
});

Using numbers for names of javascript object elements

Is the following code valid?
var i;
var objs={};
for (i=0; i <10; i++)
{
objs.i=new FooObject();
}
alert(objs.4.someMethod());
If not, how should it be rewritten to accomplish what I want?
You should edit your code as following:
var i;
var objs = {};
for (i = 0; i < 10; i++) {
objs[i] = new FooObject();
}
alert(objs[4].someMethod());
var i;
var objs = new Array();
for(i = 0; i < 10; i++)
{
objs.push(new FooObject());
}
objs[4].someMethod();
You cannot use numericals for variable names 1. If you want to reference an item by a numerical value, use an array 2. You can then access items by their key in the array. If you want to cycle through, you can use the for...in option 3. It won't matter if your keys are sequential and contiguous:
var x;
var myItems = new Array();
myItems[0] = "Foo";
myItems[9] = "Bar";
myItems[5] = "Fiz";
for (x in myItems) {
alert(myItems[x]);
}
1 http://www.w3schools.com/js/js_variables.asp
2 http://www.w3schools.com/js/js_obj_array.asp
3 http://www.w3schools.com/js/tryit.asp?filename=tryjs_array_for_in
You can't use numbers as variable names, because straight up numbers exist as their own object set in Javascript (i.e, you could think of 4 as already being a global variable that you can't override).

Categories