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.
Related
I have a multidimensional array of 100 trucks. Each truck holds several boxes.
I insert the first box of each truck by splicing from the box array to the truck array:
removed = allBoxes.splice(x, 1)[0];
trucks[i] = {0: removed};
Because I know it's the first box, I can put the {0:. But to add the next box, I want it to be dynamic.
I can insert it at the right place, but the key is undefined instead of 1 for the next box.
removed = allBoxes.splice(x, 1)[0];
trucks[i][trucks[i].length] = removed;
You can see the results here: Instead of undefined:, can it say 1? Whenever I try to add a variable in the array, it just writes out the variable string, not the value.
As #JordanBurnett mentioned, it wasn't an array. I had to count how many objects were in the array. Using the below code (from this question) gave the desired result:
var size = Object.keys(trucks[i]).length;
trucks[i][size] = removed;
Is there a way to call an addon function with a variable length. I take the user input into a variable that looks like
Uinput = [5,3,2];
Now i want to call my addon based on these numbers so it would be
addon.myaddon(5,3,2);
I also want to extend this to n inputs so if my variable of user inputs becomes
Uinput = [5,3,2,6,...,n];
then the addon will be called like
addon.myaddon(5,3,2,6,...,n);
addon.myaddon(Uinput) // will not seperate the inputs by commas are they are in the array variable, it treats the whole array as the input
This seems simple enough but it is giving me a bit of trouble. Any tips ?
Take a look at Function.prototype.apply
Uinput = [5,3,2,...,7]; // the last number in the array is in position 'n'
addon.myaddon.apply(null, Uinput);
This is equivalent to calling:
addon.myaddon(Uinput[0], Uinput[1], Uinput[2], ... , Uinput[n]);
Real example using Math.max:
// Basic example
Math.max(1,6,3,8,4,7,3); // returns 8
// Example with any amount of arguments in an array
var mySet = [1,6,3,8,4,7,3];
Math.max.apply(null, mySet); // returns 8
db = new Array("myserver", "myfolder\\mydb.nsf")
dir = getComponent("Dir").value;
div = getComponent("Div").value;
lu = #DbLookup(db, "ManagerAccess", dir + "PP" + div, "DTManagers");
var a = [];
a.push(lu);
var item:NotesItem = docBackEnd.replaceItemValue('FormReaders', #Unique(a));
item.setReaders(true);
That code is on the querySaveDocument ssjs. The result I get from the #DbLookup (when I put in a computed field) look like this:
Pedro Martinez,Manny Ramirez,David Ortiz,Terry Francona
I tried doing an #Explode(#Implode) thing on it, but it doesn't seem to work.
The error I get in the browser just tells me that the replaceItemValue line is broken.
To test it, I pushed several strings one at a time, and it worked correctly populating my FormReaders field with the multiple entries.
What am I doing wrong?
I see several problems here:
A. In cases as described by you #Dblookup in fact would return an array. If you push an array into a plain computedField control it will exactly look as that you wrote:
value1, value2, ..., valueN
A computedField doesn't know anything about multiple values etc, it just can display strings, or data that can be converted to strings.
If you want to test the return value you could try to return something like lu[0]; you then should receive the array's 1st element, or a runtime error, if lu is NOT an array. Or you could ask for the array's size using lu.length. That returns the number of array elements, or the number of characters if it's just a plain string.
B. your code contains these two lines:
var a = [];
a.push(lu);
By that you create an empty array, then push lu[] to the first element of a[]. The result is something like this:
a[0] = [value1, value2, ..., valueN],
i.e. a is an array where the first element contains another array. Since you don't want that, just use #Unique(lu) in your replaceItemValue-method.
C. I don't see why replaceItemValue would throw an error here, apart from what I wrote in topic B. Give it a try by writing lu directly to the item (first without #Unique). That should work.
D. for completeness: in the first line you used "new Array". A much better way to define your db parameters is
var db = ["myserver", "myfolder/mydb.nsf"];
(see Tim Tripcony's comment in your recent question, or see his blog entry at http://www.timtripcony.com/blog.nsf/d6plinks/TTRY-9AN5ZK)
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.
This is my code:
function insert(){
var loc_array = document.location.href.split('/');
var linkElement = document.getElementById("waBackButton");
var linkElementLink = document.getElementById("waBackButtonlnk");
linkElement.innerHTML=loc_array[loc_array.length-2];
linkElementLink.href = loc_array[loc_array.length];
}
I want linkElementLink.href to grab everything but the last item in the array. Right now it is broken, and the item before it gets the second-to-last item.
I’m not quite sure what you’re trying to do. But you can use slice to slice the array:
loc_array = loc_array.slice(0, -1);
Use pathname in preference to href to retrieve only the path part of the link. Otherwise you'll get unexpected results if there is a ?query or #fragment suffix, or the path is / (no parent).
linkElementLink.href= location.pathname.split('/').slice(0, -1).join('/');
(But then, surely you could just say:)
linkElementLink.href= '.';
Don't do this:
linkElement.innerHTML=loc_array[loc_array.length-2];
Setting HTML from an arbitrary string is dangerous. If the URL you took this text from contains characters that are special in HTML, like < and &, users could inject markup. If you could get <script> in the URL (which you shouldn't be able to as it's invalid, but some browser might let you anyway) you'd have cross-site-scripting security holes.
To set the text of an element, instead of HTML, either use document.createTextNode('string') and append it to the element, or branch code to use innerText (IE) or textContent (other modern browsers).
If using lodash one could employ _.initial(array):
_.initial(array): Gets all but the last element of array.
Example:
_.initial([1, 2, 3]);
// → [1, 2]
Depending on whether or not you are ever going to reuse the array you could simply use the pop() method one time to remove the last element.
linkElementLink.href = loc_array[loc_array.length]; adds a new empty slot in the array because arrays run from 0 to array.length-1; So you returning an empty slot.
linkElement.innerHTML=loc_array[loc_array.length-2]; if you use the brackets you are only getting the contents of one index. I'm not sure if that is what you want? The next section tells how to get more than one index.
To get what you want you need for the .href you need to slice the array.
linkElementLink.href = loc_array.slice(0,loc_array.length-1);
or using a negative to count from the end
linkElementLink.href = loc_array.slice(0,-1);
and this is the faster way.
Also note that when getting to stuff straight from the array you will get the same as the .toString() method, which is item1, item2, item3. If you don't want the commas you need to use .join(). Like array.join('-') would return item1-item2-item3. Here is a list of all the array methods http://www.w3schools.com/jsref/jsref_obj_array.asp. It is a good resource for doing this.
.slice(number you want)
if you just want the first 4 elements in an array its array.slice(3)
doing a negative number starts from the end of the array