Finding DOM Values using eq([i]) - javascript

I have the below code to get all the "Names" given in an IE form, one after the other using javascript. This script suppose to use the IE DOM explorer to get the value.
There would be one or more values that would match the query below at any given time. Therefore, I'll have to use a "For Loop" to get and assign the value to a variable one after the other. I would like to find the maximum number of occurrence to use in the For loop, by getting the value from $('tr.background-light:last').text(). This will contain a number and a name. I am stripping the number only by splitting it cnt=cnt.split(".",1) and assigning this to a variable.
Then using that as my maximum number to loop and trying to assign the value to an array. But it isn't running.
javascript:(function()
{
ver item;
var cnt=$('tr.background-light:last').text(); //getting the last background-light value which will contain the total number of Affected Client's
cnt=cnt.split(".",1); // Stripping just the number out from the above variable
for (var i =0; i <cnt.length; i++)
{
item= $("tr.background-light:eq("+i+")").text(); //looping through to get each affected client info
alert(item)
};
})();

Related

Check if element exists in array if not print not found

I am new to JS. I have task:
Given names and phone numbers, assemble a phone book that maps friends' names to their respective phone numbers. You will then be given an unknown number of names to query your phone book for. For each queried, print the associated entry from your phone book on a new line in the form name=phoneNumber; if an entry for is not found, print Not found instead.
Note: Your phone book should be a Dictionary/Map/HashMap data structure.
Input Format
The first line contains an integer, , denoting the number of entries in the phone book.
Each of the subsequent lines describes an entry in the form of space-separated values on a single line. The first value is a friend's name, and the second value is an -digit phone number.
After the lines of phone book entries, there are an unknown number of lines of queries. Each line (query) contains a to look up, and you must continue reading lines until there is no more input.
Note: Names consist of lowercase English alphabetic letters and are first names only.
Here is my code. But i cant check name exists in array or not. Js includes didnt work?
function processData(input) {
//Enter your code here
const n = parseInt(input);
const d = [];
for (var i = 1; i <= n; i++){
var line = input.split('\n').splice(i,1);
let x = line[0].split(" ");
d[x[0]] = x[1];
}
console.log(d)
let m = n;
while (true){
try{
name = input.split('\n').splice(m+1,1);
if ( d.includes(name)){
console.log(name,'=',d[name])
} else console.log('Not found')
m +=1;
}
catch(err){
break
}
}
}
name is the result of a splice on an array, which means it's an array, but you've filled d with strings, so d.includes(name) is looking for a newly-created array inside an array of strings. No array is ever equal to a string (without conversion, which includes doesn't do).
If you meant name to be the entry you removed from the array with splice (since it returns an array of removed entries), you'd need to use [0] on the end to get it:
name = input.split('\n').splice(m+1,1)[0];
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^
I haven't gone through the code to look for other issues, but that will at least look for a string in the array of strings rather than looking for an array in the array of strings.
Side note: You appear to be relying on getting an error to stop your loop, but beware that accessing beyond the end of an array is not an error in JavaScript, you just get the value undefined.

How to exclude null values from being pushed into an array?

I'm trying to do something which I thought would be extremely simple but is baffling me for some reason: I've got a function that's pushing a bunch of IDs of locations into an array and I don't want it to push these values in if they're null (the script allows user input from a Google Sheet so it's possible they'll input an incorrect value that won't get matched to an ID).
I've tried this so far:
for (var i = 0; i <= startEndDifference; i++) {
if (objectLocationInputStart != null) {
objectLocationIdsArray.push(locationMatch(objectLocationInputStart));
}
objectLocationInputStart = objectLocationInputStart + 1
}
but null values are still pushing to the array.
For context, this is referring to two cells in a Google sheet with a starting number and an ending number, and the for loop picks up all the numbers in between and matches them to an ID using the function. Everything it does is working perfectly other than passing in the null values.

Javascript equivalent of VBS redim preserve

I'm trying to rewrite some old VBScript as Javascript for an ASP.NET application and there is one line I'm not sure how to translate, and I'm not even entirely positive what it's doing.
The application essentially allows the user to enter in a new employee number to add to the database and then assign it user permissions. Don't ask me why the code is such a mess, I didn't write it originally, I'm just trying to make it work in Chrome
here's the relevant code that i've managed to translate so far:
if(form1.txtEmpno.value != ""){
var oOption;
oOption = document.createElement("OPTION");
oOption.text=form1.txtEmpno.value;
oOption.value=form1.txtEmpno.value;
form1.lstActive.add (oOption);
oOption = document.createElement("OPTION");
oOption.text="";
oOption.value="";
form1.lstPerms.add (oOption);
redim preserve arrUsers(1,ubound(arrUsers,2)+1);
arrUsers(0,ubound(arrUsers,2)) = form1.txtEmpno.value;
arrUsers(1,ubound(arrUsers,2)) = "";
form1.txtEmpno.value = "";
oOption = null;
}
here's the line in question:
redim preserve arrUsers(1,ubound(arrUsers,2)+1);
MSDN defines ReDim [Preserve] varname(subscripts) as:
The ReDim statement is used to size or resize a dynamic array that has already been formally declared using a Private, Public, or Dim statement with empty parentheses (without dimension subscripts). You can use the ReDim statement repeatedly to change the number of elements and dimensions in an array.
If you use the Preserve keyword, you can resize only the last array dimension, and you can't change the number of dimensions at all. For example, if your array has only one dimension, you can resize that dimension because it is the last and only dimension. However, if your array has two or more dimensions, you can change the size of only the last dimension and still preserve the contents of the array.
Arrays in JavaScript have different semantics to VBScript's arrays, especially in that they're actually closer to a vector than a true array, furthermore JavaScript does not provide for true N-dimensional arrays: instead you use staggered-arrays (arrays-within-arrays). Which means your VBScript cannot be syntactically converted to JavaScript.
Here's your relevant code in VBScript:
ReDim Preserve arrUsers(1,ubound(arrUsers,2)+1)
arrUsers(0,ubound(arrUsers,2)) = form1.txtEmpno.value
arrUsers(1,ubound(arrUsers,2)) = ""
We see that arrUsers is a 2-dimensional array. This will need to be converted into a staggered array, but you haven't posted the code that defines and initializes arrUsers, nor how it is used later on, so I can only work from making assumptions.
It looks to be adding 1 element to the last dimension, but the code only seems to use the extra space in the [1] subscript (i.e. it only wants the extra dimensional space for certain values of the 0th dimension instead of all values), which makes this simpler as you don't need to iterate over every 0th-dimension subscript.
JavaScript arrays have numerous function-properties that we'll use, in particular push: which appends an element to the end of an array (internally growing the buffer if necessary), and pop which removes the last (highest-indexed) element from an array (if an array is empty, it's a NOOP):
var arrUsers = [ [], [] ]; // empty, staggered 2-dimensional array
...
arrUsers[0].push( form1.txtEmpno.value );
arrUsers[1].pop();
Much simpler.
However, if this array is just part of some internal model to store and represent data then you should take advantage of JavaScript object-prototypes instead of using array indexes, as that makes the code self-describing, for example:
var User = function(empNo, name) {
this.employeeNumber = empNo;
this.name = name;
};
var users = [];
users.push( new User(1, "user 1") );
users.push( new User(23, "user 23") );
...
for(var i = 0; i < users.length; i++ ) {
alert( users[i].name );
}

javascript array show undefined when escape one index

I face a problem when tried to assign a value with a specific index. suppose I have javascript variable like
var track = new Array();
Now I assign a value for a specific index like-
track[10]= "test text";
now array has one value and it's length would be 1. But the main problem is it show it's length is 11.
alert(track.length); // 11 but I expect 1
and if I print its value then it shows like--
alert(track); // ,,,,,,,,,test text
and if I console this array then it show like below--
console.log(track); // undefined,undefined,undefined,undefined,.....,test text
I am very much confused because I assign only one value but it show 11. How it assign it's value and what characteristics array variable shows. Can anyone explain me and how to get its length 1 using below code--
var track = new Array();
track[10]= "test text";
alert(track); // test text
alert(track.length); // 1
console.log(track); // test text
The Array object automatically fills in the missing indexes. The reason it gives length 11 is because the index starts at 0.
If you are wanting to use key-value just use an object.
var track = {};
It will not have a .length value however.
javascript automatically fills in the array to push the element you want. You can get the "true" count by doing this:
track.filter(Boolean).length
However note that this will only "work" if you do not have any other elements that resolve to "false" value (eg. empty strings or setting them to false) so if you want to this, make sure you never actually set any other array elements to a falsy value so that you can use this convention. For example if you want to set other array values to a falsy value, use something like -1 instead as the thing to check.
Since you're setting the value for 10th position it's showing array size of 11
You must start from 0th position..
var track = new Array();
track[0]= "test text";
alert(track); // test text
alert(track.length); // 1
console.log(track); // test text
Try this
For such kind of operations i generally prefer the library called Underscore.js.
It abstracts array manipulations. You might want to checkout the compact method
Compact works like this:
_.compact([undefined, undefined, undefined, "test test"]) as ["test test"]
Then you can check the length of the returned array.
Though a simple approach is
filter(Boolean).length
But if you want to use the array then you might like underscore.

Javascript/jQuery Id check to drive numbering function with validation

I need help with a loop... it's probably simple but I'm having difficulty coding it up.
Basically, I need to check existing Ids for their number so I can create a unique id with a different number. They're named like this: id="poly'+i'" in sequence with my function where i is equal to the number of existing elements. Example: Array 1, Array 2, Array 3 corresponding with i=1 for the creation of Array 1, i=2 for Array 2, etc.
Right now i is based on the total number of existing elements, and my "CreateNew" function is driven off x=i+1 (so the example above, the new element will be named Array 4). The problem is that if you delete one of the middle numbers, the "Create" function will duplicate the high number. i.e. Array 1, 2, 3 delete 2, create new-> Array 1, 3, 3.
I need an if() statement to check if the array already exists then a for() loop to cycle through all i's until it validates. Not sure how to code this up.
The code I'm trying to correct is below (note I did not write this originally, I'm simply trying to correct it with my minimal JS skills):
function NewPanel() {
var i = numberOfPanels.toString();
var x = (parseInt(i)+1).toString();
$('#items').append('<div onclick="polygonNameSelected(event)" class="polygonName" id="poly'+i+'"> Array '+ x +' </div>');
$('div[id*=poly]').removeClass('selected');
$('#poly'+i).addClass('selected');
$('#poly'+i).click(function() {
selectedPolygon = i;
$('div[id*=poly]').removeClass('selected');
$(this).addClass('selected');
});
}
THANK YOU! :)
Please clarify "The problem is that if you delete one of the middle numbers, ". What do you mean by delete? Anyway, the simplest solution is to create two arrays. Both arrays will have the same created id's. Whenever an id is created in the first array, an id will be added to the second array. So when it is deleted from first array, check your second array's highest value and then create this id in first array. I hope this did not confuse you.
Well it is hard to tell why you cannot just splice the array down. It seems to me there is a lot of extra logic involved in the tracking of element numbers. In other words, aside from the index being the same, the ids become the same as well as other attributes due to the overlapping 1, 3, 3 (from the example). If this is not the case then my assumption is incorrect.
Based on that assumption, when I encounter a situation where I want to ensure that the index created will always be an appending one, I usually take the same approach as I would with a database primary key. I set up a field:
var primaryKeyAutoInc = 0;
And every time I "create" or add an element to the data store (in this case an array) I copy the current value of the key as it's index and then increment the primaryKeyAutoInc value. This allows for the guaranteed unique indexing which I am assuming you are going for. Moreover, not only will deletes not affect future data creation, the saved key index can be used as an accessor.

Categories