javascript fails when populating array - javascript

When I run the following javascript, it fails when input_array[input_array.length] = id; is not commented out. Can anyone see what is causing this?
function cat_images_low_lag () {
var input_array = new array ();
cat_images = $(".category-description").next().find("img");
cat_images.each(function () {
url = $(this).parent().attr("href");
id = url.split("id=");
id = id[1];
input_array[input_array.length] = id;
});
alert ("trst");
alert(input_array.join("\n"));
}
cheers!

First thing, replace:
var input_array = new array ();
With:
var input_array = new Array();
And use this to insert:
input_array.push(id);
Or directly add:
input_array[input_array.length] = id;
Other ways to initialize arrays:
var input_array = [];

Others noted the capitalization problem, but since you're using jQuery, a nicer way to build the Array is like this:
function cat_images_low_lag () {
var input_array = $(".category-description + * img").map(function () {
return this.parentNode.href.split("id=")[1];
}).toArray();
alert ("trst");
alert(input_array.join("\n"));
}

Your initialization of the array is incorrect
var input_array = new array ();
You should use the shorthand
var input_array = [];
or
var input_array = new Array();
Moreover, to avoid having cat_images be a variable in the global scope, you may want to consider scoping it locally like this
var cat_images = $(".category-description").next().find("img");

Related

Loop through all defined variables jquery

Hi I want to loop through all defined variables in a jquery function for pushing corresponding variable name into an array. The code is given below
function pushallvariables()
{
var list = [];
var name = /^[A-Za-z\s.]+$/;
var general = /^[A-Za-z0-9\s.\-\/]{2,20}$/;
var email = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/;
var digit = /^[+]?[0-9\s]+$/;
list.push('name');
list.push('general');
list.push('email');
list.push('digit');
}
I want to modify this function into
function pushallvariables()
{
var list = [];
var name = /^[A-Za-z\s.]+$/;
var general = /^[A-Za-z0-9\s.\-\/]{2,20}$/;
var email = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/;
var digit = /^[+]?[0-9\s]+$/;
for each(variable as var)
{
list.push(var.name);
}
}
But the modified function is not correct. How can I write the function ?
The best and clear way to do that is:
var list = {};
list.name = /^[A-Za-z\s.]+$/;
list.general = /^[A-Za-z0-9\s.\-\/]{2,20}$/;
list.email = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/;
list.digit = /^[+]?[0-9\s]+$/;
without loops, etc

Losing scope when using array.concat() and .slice() together on jquery object list

I think the code will explain it, but I'm trying to slice a jquery object list into an array and then concatenate them onto another array, multiple times. Anyways in the .each function i am getting elements in the lis variable, but when I try to slice and concat them onto the listItemArray, it isn't working. I assume I'm losing scope or there is some binding issue or something, but I can't figure out what it is. Thanks for the help. Also I know there is a jquery.slice method but I wanted to keep it vanilla if possible.
var updateSection7 = function(desired) {
var section = $('#' + _me.UUID + ' .section7yAxis');
var showedList = section.find('ul:not(:hidden)');
var listItemArray = [];
var _slice = Array.prototype.slice;
showedList.each(function(ind,el){
var lis = $(el).find('.control-group');
if(lis.length>1){
listItemArray.concat(_slice.call(lis));
}
});
}
UPDATED: Here I included both the push and concat varieties of solving the problem and did away with some wasted cpu time per requests.
var updateSection7 = function(desired) {
var lis = $('#' + _me.UUID + ' .section7yAxis ul:not(:hidden) .control-group');
var listItemArray = [];
var concatTester = [];
var _slice = Array.prototype.slice;
var _push = Array.prototype.push;
//these end up doing the same thing
_push.apply(listItemArray, _slice.call(lis));
concatTester = concatTester.concat(_slice.call(lis));
}
concat doesn't mutate the original array. It returns the new array.
Try this:
listItemArray = listItemArray.concat(_slice.call(lis));

How do I overwrite object properties in an array?

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;
}

Performing a foreach over an associative array of associative arrays

Suppose I have this setup:
var whatever = new Array();
whatever["a"] = new Array();
whatever["a"]["a"] = "test1";
whatever["a"]["b"] = "test2";
whatever["b"] = new Array();
whatever["b"]["a"] = "test3";
whatever["b"]["b"] = "test4";
And I attempt to iterate through it:
$.each(whatever, function(key, value) {
$.each(value, function(subkey, subvalue) {
//stuff with key, subkey, and subvalue here
});
});
Yet the iteration fails, commenting out the nested foreach loop will allow the page to load, so that appears to be where the problem is.
Inside the first loop, I can do something like:
alert(value["a"]);
and receive the proper value, so it seems to be a "valid" array. Where am I going wrong, since the nested loop is basically the same as the outer one?
Use objects instead of arrays.
var whatever = {};
whatever["a"] = {};
whatever["a"]["a"] = "test1";
whatever["a"]["b"] = "test2";
whatever["b"] = {};
whatever["b"]["a"] = "test3";
whatever["b"]["b"] = "test4";
http://jsfiddle.net/QwT8W/

Storing value in a dynamically defined Javascript array?

I'm writing a script that will split the element's ID from the format 'note-1192' (for example) and place it into an array:
var timers = new Array();
$('.notes').keyup(function(){
var timerVariable = $(this).attr('id').split("-");
timerVariable = timerVariable[0];
timerVariable = timerVariable.replace('note', '');
alert(timerVariable); // 1192
timers[timerVariable] = timerVariable;
alert(timers.join('\n')); // blank
});
It's not storing the variable into the array at all, when I alert the 'timers array' it's empty, but when I alert the 'timerVariable' it comes out just fine.
Any suggestions would be very welcome, thanks!
The problem is the index syntax your are using is setting a named property on the array object not adding an element. To add an element to the array use push
timers.push(timerVariable);
try
Array:
var timers = new Array();
timers.push(timerVariable);
Hash:
var timers = {};
timers[timerVariable] = timerVariable;
Use push method of array to add an element to array.
timers.push(timerVariable);
var timers = new Array();
$('.notes').keyup(function(){
timers.push($(this).attr('id').split("-")[0]);
});
Despite the assertion in the comment,
"note-1192".split("-")[0].replace("note", "") === ""
The simple fix would be to get the second, rather than first, element of the split string:
var timerVariable = $(this).attr('id').split("-")[1];
To ensure you get a number, you could use a regular expression.
var timerId = $(this).attr('id').match(/\d+/);
if (timerId) {
timerId=timerId[0];
...
}
I think this is what you are trying to do:
var timers = new Array();
$('.notes').keyup(function(){
var temp = $(this).attr('id').split("-");
timerValue = temp[0];
timerID = temp[1];
alert(timerID); // 1192
timers[timerID] = timerValue;
alert(timers.join('\n'));
});
With the way you currently have it, timerVariable will be '' in the end, and so what you're doing at the end is really the same as:
timers[''] = '';

Categories