value is not added to multidimensional array - javascript

The first time the function fires I get this result:
output1:test
The output2 2 alert is not firing. I know something is probably undefined in alert Does anyone know why the value won't be added in the multidimensional array?
I expect this to display after the false1:
output2:test2
Also if you want to fiddle with the code here it is:
https://jsfiddle.net/ndf0sjgf/1/
var carSelectedArray = [
[null]
];
addRow(carSelectedArray);
addRow(carSelectedArray);
function addRow(carSelectedArray) {
var arrayempty = false;
if (carSelectedArray[0][0] == null || carSelectedArray.length == 0) {
arrayempty = true;
} else {
arrayempty = false;
}
if (arrayempty == true) {
carSelectedArray[0][0] = "test";
alert("output1:" + carSelectedArray[0][0]);
} else {
carSelectedArray[1][0] = "test2";
alert("output2:" + carSelectedArray[1][0]);
}
}

Your loop works well, however your didn't define your array well.
there is only 1 dimension here :
var carSelectedArray = [[null]];
So replace with this :
var carSelectedArray = [[],[]];
PS : null is not required
and at the beginning in your function, you define arrayempty to false, so you can remove this :
else {
arrayempty = false;
}
Solution here : https://plnkr.co/edit/Qikalr0jc54R3MRSea4G?p=preview
var carSelectedArray = [[],[]];
addRow(carSelectedArray);
addRow(carSelectedArray);
function addRow(carSelectedArray) {
var arrayempty = false;
if (carSelectedArray[0][0] == null || carSelectedArray.length == 0) {
arrayempty = true;
}
if (arrayempty == true) {
carSelectedArray[0][0] = "test";
alert("output1:" + carSelectedArray[0][0]);
} else {
carSelectedArray[1][0] = "test2";
alert("output2:" + carSelectedArray[1][0]);
}
}

Related

Javascript How to check the length of multiple variables and return the result in an efficient way?

At the moment I have an if the condition that checks if any of the string variable lengths is greater than 2 if true check for another condition, else console.log the output.
var previous_data_change = 'last_changed on 10/01/2019 13:56:34';
var current_data_change= "";
var current_data_end = "";
var current_data_profile = "normal";
// check for changes
if (
previous_data_change.length >= 2 ||
current_data_start.length >= 2 ||
current_data_end.length >= 2 ||
current_data_profile.length >= 2
) {
if (previous_data_change.includes("last_changed")) {
console.log(`last change comments: ${previous_data_change}`)
}
} else {
console.log(`no change in previous record`)
}
i have tried refactoring it using some,
var previous_data_change = 'last_changed on 10/01/2019 13:56:34';
var current_data_change= "";
var current_data_end = "";
var current_data_profile = "normal";
var filter_col = [
previous_data_change,
current_data_change,
current_data_end,
current_data_profile
];
change_boolean = filter_col.some((element) => element.length >= 2);
if (change_boolean && previous_data_change.includes("last_changed")) {
console.log(`last change comments: ${previous_data_change}`);
} else {
console.log("no change in previous record");
}
is there any way to shorten it further?
Since you want any of them to be length greater than 2. You can simply merge them instead of writing 4 if conditions.
var previous_data_change = 'last_changed on 10/01/2019 13:56:34';
var current_data_change= "";
var current_data_end = "";
var current_data_profile = "normal";
var string_to_check = previous_data_change + current_data_start + current_data_end + current_data_profile;
// check for changes
if (string_to_check.length < 2) {
console.log(`no change in previous record`)
return false;
}
if (previous_data_change.includes("last_changed")) {
console.log(`last change comments: ${previous_data_change}`)
return true;
}

How to put a condition in jQuery's map function?

I am trying to put a condition in jQuery's map function. My issue is that I don't want the same number in the map function value. When it is the same I want to display an alert box. My map function code is like this:
var rankbox= $('input[type=text][class = cate_rank]').map(function() {
return this.value;
}).get();
If I get a value like 1,2,3,4,5 it's ok, but if I get a value like 1,2,3,2,5, I want to display an alert box. Is it possible?
How to put a condition in jQuery's map function?
function change_rank() {
var rankbox= $('input[type=text][class = cate_rank]').map(function() {
if() {
} else { }
return this.value;
}).get();
var vals = []
$('input[type=text][class = cate_rank]').each(function(){
if($(this).val() && (typeof vals[$(this).val()] == 'undefined')){
vals[$(this).val()] = 1;
var last_val = $(this).val();
}else if($(this).val() && (typeof last_val != 'undefined') && parseInt(last_val) > parseInt($(this).val())){
alert('Whooah! Something went terribly wrong! Inputs don\'t have values ordered incrementally!');
}else{
alert('Whooah! Something went wrong! We got two inputes with same value!');
}
});
Check this,
var rankbox= $(".test").map(function() {
return this.value;
}).get();
var sorted_arr = rankbox.slice().sort();
var results = [];
for (var i = 0; i < rankbox.length - 1; i++) {
if (sorted_arr[i + 1] == sorted_arr[i]) {
results.push(sorted_arr[i]);
}
}
var rankbox= $(".test").map(function() {
if($.inArray(this.value, results) > -1){
alert(this.value+" is duplicate");
}
return this.value;
}).get();
I took reference of this link
If you are Looking to check dup you can try this:
var x=[1,2,3,2,5]
var has=!x.every(function(v,i) {
return x.indexOf(v) == i;
});
console.log(has);//true means dup found else not found.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
you can try with a object. check this:
function change_rank() {
var temp = {};
var rankbox= $('input[type=text][class = cate_rank]').map(function() {
if(temp[this.value]==undefined) {
temp[this.value] = this.value;
} else {
alert('the same value');
}
return this.value;
}).get();

Minimizing CSS "margin-" rules to one "margin:" rule with Javascript

I have entered each "margin-" CSS rule in an array giving me:
[ 'margin-left:15px', 'margin-right:25px', 'margin-top:100px' ]
I am trying to create an array that displays the values in the right order
var margRed1:[newMargTop, newMargRight, newMargBottom,newMargLeft];
My code is:
var directionRegex = /\d{2,3}px/;
var margRed = "margin: ";
var noMarg = "0px";
var margRed1 = [];
for (var i = 0; i < cssClassArrayMargin.length; i++) {
if (cssClassArrayMargin[i].match('-top')) {
var margTop = directionRegex.exec(cssClassArrayMargin[i]);
var newMargTop = margTop[0];
} else {
newMargTop = noMarg
}
if (cssClassArrayMargin[i].match('-right')) {
var margRight = directionRegex.exec(cssClassArrayMargin[i]);
var newMargRight = margRight[0];
} else {
newMargRight = noMarg
};
if (cssClassArrayMargin[i].match('-bot')) {
var margBot = directionRegex.exec(cssClassArrayMargin[i]);
var newMargBot = margBot[0];
} else {
newMargBot = noMarg
}
if (cssClassArrayMargin[i].match('-left')) {
var margLeft = directionRegex.exec(cssClassArrayMargin[i]);
var newMargLeft = margLeft[0];
} else {
newMargLeft = noMarg
}
}
if (newMargTop || newMargRight || newMargBot || newMargLeft === undefined) {
newMargTop = noMarg;
newMargBot = noMarg;
}
console.log(margRed1)
It gives me the following array:
[ '100px', '25px', undefined, '15px' ]
I do not understand why it does not display 0px and instead displays undefined.
Thanks
why don't you try to initial this "margRed1" array like this first?
var margRed1 = [ '0px', '0px', '0px', '0px' ];
and then remove these code
if (newMargTop || newMargRight || newMargBot || newMargLeft === undefined) {
newMargTop = noMarg;
newMargBot = noMarg;
}
[ 'margin-left:15px', 'margin-right:25px', 'margin-top:100px' ]
In the above code the entered value does not have all four value but in array there are four values
var margRed1:[newMargTop, newMargRight, newMargBottom,newMargLeft];
Give margin-bottom:0 where you have entered the values like this
[ 'margin-left:15px', 'margin-right:25px', 'margin-top:100px', 'margin-bottom:0px' ]
You need to read about variable hoisting. You are declaring variables in blocks, which means they are hoisted to the top of the function and start their lives as undefined. This is very poor code:
if (someCondition) {
var x = 0;
} else {
x = 1;
}
It would be better written as:
var x;
...
x = someCondition ? 0 : 1;
Also the line:
if (newMargTop || newMargRight || newMargBot || newMargLeft === undefined) {
Is this intentional? You are testing for newMartTop, newMargRight, or newMartBot to be truthy, or newMargLeft to be undefined. You would be better to omit the === undefined altogether.

How does Javascript evaluate the right parenthesis?

I'm working on a calculator that takes an expression such as (5+4) and evaluates it by passing the buttons pressed to an array, and then building a parse tree from the data in the array.
What's interesting/strange, is that my code won't push the value of the right parenthesis to the array. Here is my code, could someone help me out?
The console.log activeButton shows that is the value of the button being pressed, but even when I placed calcArray.push() outside the if statements it would not push ) to an array.
$(document).ready(function(){
var calcArray = new Array();
$("input").click(function(){
var activeButton = this.value;
console.log(activeButton);
if(!isNaN(activeButton))
{
calcArray.push(parseInt(activeButton));
console.log(calcArray);
}
else if(activeButton === "=")
{
evaluate(buildTree(calcArray));
calcArray = [];
}
else
{
calcArray.push(activeButton);
}
});
});
The BuildTree code:
function BinaryTree(root) {
this.root = root;
this.activeNode = root;
}
function Node(element){
this.element = element;
this.parent;
this.rightChild;
this.leftChild;
this.setLeft = function(node){
this.leftChild = node;
node.parent = this;
};
this.setRight = function(node){
this.rightChild = node;
node.parent = this;
};
}
//methods
var buildTree = function(array)
{
var tree = new BinaryTree(new Node(null));
for(var i = 0; i < array.length; i++)
{
var newNode = new Node(array[i]);
if(array[i] == "(")
{
newNode.element = null;
tree.activeNode.setLeft(newNode);
tree.activeNode = newNode;
}
else if(array[i] == "+" || array[i] == "-" || array[i] == "/" || array[i] == "*")
{
tree.activeNode.element = newNode.element;
tree.activeNode.setRight(new Node(null));
tree.activeNode = tree.activeNode.rightChild;
}
else if(array[i] == ")")
{
if(tree.activeNode.parent == null)
{
;
}
else
{
tree.activeNode = tree.activeNode.parent;
tree.root = tree.activeNode;
}
}
else
{
tree.activeNode.element = newNode.element;
tree.activeNode = tree.activeNode.parent;
}
}
return tree.activeNode;
}
var evaluate = function(node){
var newNode1, newNode2;
newNode1 = new Node(null);
newNode1.parent = node;
newNode2 = new Node(null);
newNode2.parent = node;
if(node.leftChild == null && node.rightChild == null)
return node.element;
else{
newNode1.element = evaluate(node.leftChild);
newNode2.element = evaluate(node.rightChild);
if(newNode1.parent.element == "+")
{
return Number(newNode1.element) + Number(newNode2.element);
}
if(newNode1.parent.element == "-")
{
return newNode1.element - newNode2.element;
}
if(newNode1.parent.element == "*")
{
return newNode1.element * newNode2.element;
}
else
{
return newNode1.element / newNode2.element;
}
}
};
I just tried this out using your code and it worked fine passing the value as a string:
function pushButton (value) {
var activeButton = value;
console.log(activeButton);
if(!isNaN(activeButton))
{
calcArray.push(parseInt(activeButton));
console.log(calcArray);
}
else if(activeButton === "=")
{
evaluate(buildTree(calcArray));
calcArray = [];
}
else
{
calcArray.push(activeButton);
}
};
You aren't ever printing out the array in the last case (which is where the right paren would go), so are you sure it's not on the array and you just aren't seeing the visual feedback?
If so, we need to see more of your code. Try and setup a jsfiddle.

Passing variable between javascript functions not working?

I tried using this method to pass a variable to the next function:
function a(form, ctr) {
var a = form;
var b = ctr;
b(ctr);
}
function b(ctr) {
var b = ctr;
}
The exact code is a lot more complicated as i'm using the POST method with ajax: function a begins upon a click and uses both the form and ctr parameters - it then goes to function b which only needs ctr - however this method of passing the variable hasn't worked. Any better solution?
function updateQuestion(form, ctr) {
console.log("Called updateQuestion");
var str1 = "toggleDiv";
var str2 = ctr;
var id = str1.concat(str2);
var divVar = document.getElementById(id);
console.log(divVar);
var getdate = new Date(); //Used to prevent caching during ajax call
if(XMLHttpRequestObject) {
console.log("XMLHttpRequestObject = TRUE");
var myVar = form.create_mcq_question.value;
console.log("MyVar = " + myVar);
var formQuestion = document.getElementById("formQuestion");
console.log("1");
XMLHttpRequestObject.open("POST","hiddent",true);
console.log("2");
XMLHttpRequestObject.onreadystatechange = handleServerResponse;
console.log("3");
XMLHttpRequestObject.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
console.log("4" + document.getElementById("create_mcq_question").value);
var mcqid;
var mcqQuestion;
var mcqAnswerCorrect;
var mcqAnswerWrong1;
var mcqAnswerWrong2;
var mcqAnswerWrong3;
var mcqExplanation;
var error = 0;
if (form.create_mcq_question.value == "" || form.create_mcq_question.value == null ) {
error = 1;
}
else {
mcqQuestion = form.create_mcq_question.value
}
if (form.create_mcq_answer_correct.value == "" || form.create_mcq_answer_correct.value == null) {
mcqAnswerCorrect = "";
error = 1;
}
else {
mcqAnswerCorrect = form.create_mcq_answer_correct.value
}
if ((form.create_mcq_answer_wrong1.value == "" || form.create_mcq_answer_wrong1.value == null) && (form.create_mcq_answer_wrong2.value == "" || form.create_mcq_answer_wrong2.value == null) && (form.create_mcq_answer_wrong3.value == "" || form.create_mcq_answer_wrong3.value == null)) {
error = 1;
}
if (form.create_mcq_answer_wrong1.value == "" || form.create_mcq_answer_wrong1.value == null) {
mcqAnswerWrong1 = "";
}
else {
mcqAnswerWrong1 = form.create_mcq_answer_wrong1.value
}
if (form.create_mcq_answer_wrong2.value == "" || form.create_mcq_answer_wrong2.value == null) {
mcqAnswerWrong2 = "";
}
else {
mcqAnswerWrong2 = form.create_mcq_answer_wrong2.value
}
if (form.create_mcq_answer_wrong3.value == "" || form.create_mcq_answer_wrong3.value == null) {
mcqAnswerWrong3 = "";
}
else {
mcqAnswerWrong3 = form.create_mcq_answer_wrong3.value
}
if (form.create_mcq_explanation.value == "" || form.create_mcq_explanation.value == null) {
mcqExplanation = "";
}
else {
mcqExplanation = form.create_mcq_explanation.value
}
if (error == 0) {
XMLHttpRequestObject.send("create_mcq_question=" + mcqQuestion +
"&create_mcq_correct_answer=" + mcqAnswerCorrect +
"&create_mcq_wrong_answer1=" + mcqAnswerWrong1 +
"&create_mcq_answer_wrong2=" + mcqAnswerWrong2 +
"&create_mcq_answer_wrong3=" + mcqAnswerWrong3 +
"&create_mcq_explanation=" + mcqExplanation +
"&mcqid=" + mcqid );
console.log("5");
handleServerResponse(ctr);
}
else {
document.getElementById("divVar").innerHTML="Cannot update question - please ensure all required fields are filled!";
}
}
}
function handleServerResponse(ctr) {
var str1 = "toggleDiv";
var str2 = ctr;
var id = str1.concat(str2);
var divVar = document.getElementById(id);
console.log("Handle server response called");
if (XMLHttpRequestObject.readyState == 1) {
console.log("Loading");
document.getElementById(divVar).innerHTML="<img src=\"hidden">";
}
if (XMLHttpRequestObject.readyState == 4) {
console.log("4");
if(XMLHttpRequestObject.status == 200) {
document.getElementById(divVar).innerHTML=XMLHttpRequestObject.responseText; //Update the HTML Form element
console.log("divVar found");
console.log(divVar);
}
else {
document.getElementById(divVar).innerHTML="There was a problem updating your question - please try again!"; //Update the HTML Form element
console.log("divVar not found");
console.log(divVar);
}
}
}
And the button which starts the whole thing off:
<input type="button" value="Update My Question!" onclick="updateQuestion(this.form,<?php echo" $ctr"; ?>)">
Firebug showing the first function working, and calling the second one, which doesn't get the variable:
[02:21:42.106] Called updateQuestion
[02:21:42.106] [object HTMLDivElement]
[02:21:42.106] XMLHttpRequestObject = TRUE
[02:21:42.106] MyVar = Gram- bacteria are stained purple with gram staining, while gram+ bacteria are stained pink.
[02:21:42.106] 1
[02:21:42.107] 2
[02:21:42.107] 3
[02:21:42.107] 4Gram- bacteria are stained purple with gram staining, while gram+ bacteria are stained pink.
[02:21:42.108] Handle server response called
[02:21:42.108] Loading
[02:21:42.108] 5
[02:21:42.108] Handle server response called
[02:21:42.109] Loading
[02:21:42.649] Empty string passed to getElementById(). # hidden
[02:21:42.649] TypeError: document.getElementById(...) is null # hidden
[02:21:42.647] Handle server response called
[02:21:42.648] 4
There is already a variable called 'b' inside your function scope. That's why you get the error. If they are global functions, you can use:
function a(form, ctr) {
var a = form;
var b = ctr;
window.b(ctr);
}
function b(ctr) {
var b = ctr;
}
The following makes no sense really:
var b = ctr;
b(ctr);
Here the variable b is treated and invoked as function, and you pass a reference to itself as the parameter. Is that really our intention?
Edit: Now with the additional info, the problem is easy to explain. If you look at your log, you'll notice that the handleServerResponse is invoked several times. The first time "ctr" is passed as expected.
The problem is here:
XMLHttpRequestObject.onreadystatechange = handleServerResponse;
This sets a callback, and the callback will invoke your function without the "ctr" of course, which is why your code runs as it does. You could use an anonymous function so that a closure is used:
XMLHttpRequestObject.onreadystatechange = function() { handleServerResponse(ctr); };
You may want to read JavaScript: The Good Parts by Crockford, I think it would help to improve your JS coding significantly.

Categories

Resources