i want to remove array element, but giving error while using splice,
i m using following function
with myAra as global var,
but in console ,it is giving me an error, TypeError: myAra.splice is not a function
var myAra = Array();
function charCounts(e,textAreaId)
{
myAra = $("#"+textAreaId).val();
var countNewLines = stringOccurrences(myAra, "\n");
if(myAra.length>75)
{
for (var i = 75; i >myAra.length; i++)
{
myAra.splice(i, 1);
}
$("#"+textAreaId).val(myAra);
}
}
This is a nice example of why globals are EVIL, sure you declared the variable an array (badly):
var myAra = Array()(I’ll explain at the end what’s bad about this), but later on:You’ve reassigned a string to the array, so the variable now references a string constant, and cannot be used as an Array (not safely, in a X-browser way at least).
Array()is bad, why? Well, for starters, you’re calling a constructor, but you’re not using thenewkeyword. With arrays that’s not a big problem (it’ll return a new instance all the same), but when you start defining your own objects, and constructors, you’ll find yourself up to your neck in globals.Also, suppose you wanted an array and initialize the first element to an int:
var anArray = new Array(2);, you won’t get an array that looks like this:anArray[0] === 2, you’ll getanArray === [undefined,undefined]. Compare that tovar anArray('2')–> [‘2’]. Given the fact that JS is loosely typed, and you’ll often use variables when initializing an array, it’s hard to tell weather or not you’re passing a numeric string or a number to the constructor.The best way to initialize arrays is by using the literal notation:
[2,3,4], as an added bonus, it requires less typing, too