i want to pass an array to a function and work on it,but i am afraid ,error occurs saying board_pt is undefined. What is the problem? This is the code :
function set_boardPoint( board_pt,turn)
{
var no = board_pt.number-1;
board[no].row = board_pt.row;
board[no].col = board_pt.col;
board[no].x = board_pt.x;
board[no].y = board_pt.y;
board[no].value = turn;
board[no].number = board_pt.number;
}
board is a global array already defined
The problem is that board_pt have only 1 item, and js in these case know board_pt as object:
function set_boardPoint( board_pt,turn)
{
var no = board_pt.number-1;
if( board[no] != undefined )
{
board[no].row = board_pt.row;
board[no].col = board_pt.col;
board[no].x = board_pt.x;
board[no].y = board_pt.y;
board[no].value = turn;
board[no].number = board_pt.number;
}else
{
board.row = board_pt.row;
board.col = board_pt.col;
board.x = board_pt.x;
board.y = board_pt.y;
board.value = turn;
board.number = board_pt.number;
}
}
If board_pt is a real array, then it's unlikely that it has a property named number. Do you mean length?
From your comments, you have to define the previous_boardPoint as an array. To declare a array in javascript, you need to have - var previous_boardPoint = []; in your code. Also have each elements defined (if you have any) like previous_boardPoint[0] = val1; previous_boarPoint[1] = val2; etc.
If these things are not in your code, then in all likely possibilities, you will get board_pt as undefined in your function set_boardPoint.
Related
I have this String:
['TEST1-560', '{"data":[{"price":0.0815,"volume":0.2,"car":"BLUE"}],"isMasterFrame":false}']
I want to get the keys 'TEST1-560' which is always fist and "car" value.
Do you know how I can implement this?
This is a very, very scuffed code, but it should work for your purpose if you have a string and you want to go through it. This can definitely be shortened and optimized, but assuming you have the same structure it will be fine.:
// Your data
var z = `['TEST1-560', '{"data":[{"price":0.0815,"volume":0.2,"car":"BLUE"}],"isMasterFrame":false}']`;
var testName = z.substring(2).split("'")[0];
var dividedVar = z.split(",");
for (var ind in dividedVar) {
if (dividedVar[ind].split(":")[0] === '"car"') {
var car = dividedVar[ind].split(":")[1].split("}")[0].substring(1,dividedVar[ind].split(":")[1].split("}")[0].length-1);
console.log(car)
}
}
console.log(testName);
output:
BLUE
TEST1-560
In a real application, you don't need to log the results, you can simply use the variables testName,car. You can also put this in a function if you want to handle many data, e.g.:
function parseData(z) {
var testName = z.substring(2).split("'")[0];
var dividedVar = z.split(",");
for (var ind in dividedVar) {
if (dividedVar[ind].split(":")[0] === '"car"') {
var car = dividedVar[ind].split(":")[1].split("}")[0].substring(1, dividedVar[ind].split(":")[1].split("}")[0].length - 1);
}
}
return [testName, car]
}
This will return the variables values in an array you can use
const arr = ['TEST1-560', '{"data":[{"price":0.0815,"volume":0.2,"car":"BLUE"}],"isMasterFrame":false}']
const testValue = arr[0];
const carValue = JSON.parse(arr[1]).data[0].car;
console.log(testValue);
console.log('-----------');
console.log(carValue);
If your structure is always the same, your data can be extracted like above.
So i've got an array of 9 strings, predefined, and when i try to call them out in a function they come out as undefined, i don't really know what am i doing wrong :/
function checkAns(){
var nr_pytania = (document.getElementById("q_id").value)-1;
var odpowiedz = document.getElementById("answer").value;
var odpowiedzi = ["Mazury", "Korfanty", "Paderewski", "Wersalski", "Zaolzie", "Orlęta", "Wisła", "Haller", "Gdańsk"];
console.log(odpowiedzi[0].charAt[0]);
if(odpowiedz == odpowiedzi[nr_pytania])
{
document.getElementById("answer").value = "POPRAWNE!";
for(var i=0; i<odpowiedzi[nr_pytania].length; i++)
{
document.getElementById("letter"+nr_pytania+i).innerHTML = odpowiedzi[nr_pytania].charAt[i];
}
}
else
{
document.getElementById("answer").value = "Odpowiedź błędna!";
}
}
So, the part that is the most important to me is:
var odpowiedzi = ["Mazury", "Korfanty", "Paderewski", "Wersalski", "Zaolzie", "Orlęta", "Wisła", "Haller", "Gdańsk"];
console.log(odpowiedzi[0].charAt[0]);
Because the console returns undefined, and im not really sure why :(
var odpowiedzi = ["Mazury", "Korfanty", "Paderewski", "Wersalski", "Zaolzie", "Orlęta", "Wisła", "Haller", "Gdańsk"];
console.log(odpowiedzi[0].charAt(0));
You need to change it from charAt[0] to charAt(0).
Additional reading for String.prototype.charAt().
You could simply use odpowiedzi[0][0] - no need to use charAt() :)
So , I want to test many conditions, for different values... right now is just a bunch of if,else statements...
But it looks ugly im sure there must be a better way...
any ideas ?
Im thinking maybe with loops but or putting all vars in an array, but I cant figure out how..
Thx!
var dataObject = {}
if (newState.playerId){
dataObject["filter[player_id]"] = newState.playerId
}else{
dataObject["filter[player_id]"] = this.state.playerId
}
if (newState.pageLimit){
dataObject ["page[limit]"] = newState.pageLimit
}else{
dataObject["page[limit]"] = this.state.pageLimit
}
if (newState.timeFrom){
dataObject["time[from]"] = newState.timeFrom
}else{
dataObject["time[from]"] = this.state.timeFrom
}
if (newState.timeTo){
dataObject["time[to]"] = newState.timeTo
}else{
dataObject["time[to]"] = this.state.timeTo
}
if (newState.gameId){
dataObject["filter[game_id]"] = newState.gameId
}else{
dataObject["filter[game_id]"] = this.state.gameId
}
if (newState.customerId){
dataObject["filter[customer_id]"] = newState.customerId
}else{
dataObject["filter[customer_id]"] = this.state.customerId
}
if (newState.currency){
dataObject["filter[currency]"] = newState.currency
}else{
dataObject["filter[currency]"] = this.state.currency
}
if (newState.variant){
dataObject["filter[locale]"] = newState.locale
}else{
dataObject["filter[locale]"] = this.state.locale
}
if (newState.variant){
dataObject["filter[demo]"] = newState.demo
}else{
dataObject["filter[demo]"] = this.state.demo
}
Use the or (||) operator taking benefit of the short circuit evaluation, e.g.
dataObject["filter[player_id]"] = newState.playerId || this.state.playerId
Reducing your condition
First, you can use javascript's || operator and change:
if (newState.playerId){
dataObject["filter[player_id]"] = newState.playerId
}else{
dataObject["filter[player_id]"] = this.state.playerId
}
To the much reduced:
dataObject["filter[player_id]"] = newState.playerId || this.state.playerId;
DRY up your code
You can use an array of properties:
var propertyList = ["playerId", "pageLimit", "timeFrom" /* etc. */]
Because object properties can be referenced using square brackets you can loop through them like this:
propertyList.forEach(function(property){
dataObject[property] = newState[property] || this.state[property]
});
Disclaimer: This solution is not taking into account your embedded objects (like "filter") and the slight variations in your naming schemes (like "player_id" vs "playerId").
Three solutions occur to me:
Use consistent naming conventions
In other words in the dataObject that you build have the same naming pattern as your state object.
Use a helper function
Convert the names in your for loop using some kind of consistent pattern that changes playerId to player_id when those kinds of changes need to be done. (this will still not work if you plan to use "filter", "time" or "page".
Use objects/arrays (as in #ssube's solution)
You could also use an array or an object to translate your property names between objects. I won't give you an example - #ssube has done so already.
You have a recurring pattern here:
if (newState[srcField]) {
dataObject[destField] = newState[srcField]
} else {
dataObject[destField] = this.state[srcField]
}
Thanks to JS' handling of the OR operator, you can simplify that to:
dataObject[destField] = newState[srcField] || this.state[srcField];
Since you have the field names, you can set up a loop like:
var dataObject = {};
var fields = [
['playerId', 'filter[player_id]'],
['pageLimit', 'page[limit]']
];
fields.forEach(function (field) {
var src = field[0], dest = field[1];
dataObject[dest] = newState[src] || this.state[src];
});
and voila, the fields will be copied across with appropriate renaming.
var dataObject = {};
dataObject['filter[player_id]'] = newState.playerId || this.state.playerId;
dataObject['filter[game_id]'] = newState.gameId || this.state.gameId;
dataObject['filter[customer_id]'] = newState.customerId || this.state.customerId;
dataObject['filter[currency]'] = newState.currency || this.state.currency;
dataObject['filter[locale]'] = newState.variant ? newState.locale : this.state.locale;
dataObject['filter[demo]'] = newState.variant ? newState.demo: this.state.demo;
dataObject['page[limit]'] = newState.pageLimit || this.state.pageLimit;
dataObject['time[from]'] = newState.timeFrom || this.state.timeFrom;
dataObject['time[to]'] = newState.timeTo || this.state.timeTo;
I would like to overwrite a certain allOrders[i] with data, similar to how I create a new one. For some reason I can't figure out what to search on.
I have an array of objects allOrders.
I have an object BusinessCard. I take the form fields, serialize() them, clean up the data with a regex, then push the them into an array.
allOrders.push(new BusinessCard(currentOrder.quantity, currentOrder.FullName, currentOrder.Title, currentOrder.CellNumber, currentOrder.OfficeNumber, currentOrder.FaxNumber, currentOrder.EmailAddress, currentOrder.Address, currentOrder.website, currentOrder.price));
I've tried searching for overwriting existing object properties in an array and the likes and haven't figured out what to do here.
My best guess was allOrders[i].push -- but it seems to me that I have to write a new function to replace each property in the object.
Right now I am using(because using serialize() on the form inputs doesn't help me at all:
allOrders[i].quantity = $('#bcQuantity').val();
allOrders[i].fullname = $('#fullName').val();
allOrders[i].title = $('#Title').val();
allOrders[i].cell = $('#CellNumber').val();
allOrders[i].office = $('#OfficeNumber').val();
allOrders[i].fax = $('#FaxNumber').val();
allOrders[i].email = $('#EmailAddress').val();
allOrders[i].address = $('#Address').val();
allOrders[i].website = $('#website').val();
allOrders[i].price = $('#bcCostBeforeCart').text();
There has to be a smarter way to do this. Thank you.
EDIT:
function getFormData(formId) {
var currentForm = '#' + formId;
var currentPrice = $('#bcCostBeforeCart').text();
var currentFormData = $(currentForm).serialize();
var currentFormDataFinal = currentFormData + '&price=' + currentPrice;
return JSON.parse('{"' + decodeURI(currentFormDataFinal.replace(/\+/g, " ").replace(/&/g, "\",\"").replace(/=/g, "\":\"")) + '"}');
}
MEANING i could be using
currentOrder = getFormData('businessCardForm');
then
allOrders[i] = currentOrder;
Seems odd that you would be updating all items with the selector's you're using, but I would wrap up getting the updated order information then, you can run thru a loop.
Depending on your output, as long as it's outputing the respective properties and values of an order object you could just do:
for(int i =0; i < allOrders.length; i++){
var currentFormId = '' // update this for each iteration.
allOrders[i] = getFormData(currentFormId);
}
allOrders[i] = getUpdatedOrder();
function getUpdatedOrder() {
var order = {};
order.quantity = $('#bcQuantity').val();
order.fullname = $('#fullName').val();
order.title = $('#Title').val();
order.cell = $('#CellNumber').val();
order.office = $('#OfficeNumber').val();
order.fax = $('#FaxNumber').val();
order.email = $('#EmailAddress').val();
order.address = $('#Address').val();
order.website = $('#website').val();
order.price = $('#bcCostBeforeCart').text();
return order;
}
This question already has an answer here:
when i run my code I get the following result []object object] [object object] but should be giving me an ordered array
(1 answer)
Closed 8 years ago.
below is the code that i used to create a range object within my overall programme
function parseRangeString(id, range) {
var myRangeString = range;
var myRangeStringArray = myRangeString.split(/[\s]+/);
var myMax;
var myMin;
var myMinOp;
var myMaxOp;
var myMaxInc = false;
var myMinInc = false;
var op1;
var op2;
var cons1;
var cons2;
op1 = myRangeStringArray[0];
cons1 = parseFloat(myRangeStringArray[1]);
if (myRangeStringArray[2] != null) {
op2 = myRangeStringArray[3];
cons2 = parseFloat(myRangeStringArray[4]);
}
if (cons1 < cons2) {
myMin = cons1;
myMinOp = op1;
myMax = cons2;
myMaxOp = op2;
} else {
myMin = cons2;
myMinOp = op2;
myMax = cons1;
myMaxop = op1;
}
if (myMaxOp.indexOf('=') != -1) {
myMaxInc = true;
}
if (myMinOp.indexOf('=') != -1) {
myMinInc = true;
}
firstRange = new Range(id, myMin, myMax, myMinInc, myMaxInc); //gives back a range object
return firstRange;
}
Now i need to make another function that converts the range object to string, help needed asap because i am stuck atm!
You can overwrite the standard toString function on your javascript objects to make them return whatever you want. Consider this example (demo):
var a = { some_property:'this could be coming from the user' }; // create a new object
a.toString = function(){
// in here, the "this" will point to the object in "a" variable. (well, at least mot of the times)
return this.some_property;
};
console.log(''+a); // force the object to string
If you create a lots of object like this, consider using the prototype of them to place the toString function, will be more efficient, MDN has great examples.
Well i guess i give the same answer every day. :)
JSON.stringify( range );