JavaScript empty array - javascript

https://stackoverflow.com/a/1234337/1690081
shows that array.length = 0;will empty array but in my code it doesn't
here's an sample:
window.onload = draw;
window.onload = getFiles;
var namelist = [];
function draw(){
// assing our canvas to element to a variable
var canvas = document.getElementById("canvas1");
// create html5 context object to enable draw methods
var ctx = canvas.getContext('2d');
var x = 10; // picture start cordinate
var y = 10; // -------||---------
var buffer = 10; // space between pictures
for (i=0; i<namelist.length; i++){
console.log(namelist[i])
var image = document.createElement('img');
image.src = namelist[i];
canvas.appendChild(image);
ctx.drawImage(image,x,y,50,50);
x+=50+buffer;
}
}
function getFiles(){
namelist.length = 0;// empty name list
var picturesFiles = document.getElementById('pictures')
picturesFiles.addEventListener('change', function(event){
var files = picturesFiles.files;
for (i=0; i< files.length; i++){
namelist.push(files[i].name);
console.log(namelist)
}
draw();
}, false);
}
after i call getFiles() second time. It doesn't remove the previous list, just appends to it. any idea why?

You should empty the array in the event handler, not getFiles which is only called once per pageload. It is actually doing nothing because the array is already empty when the page loads.
picturesFiles.addEventListener('change', function(event){
namelist.length = 0; //empty it here
var files = picturesFiles.files;
for (i=0; i< files.length; i++){
namelist.push(files[i].name);
console.log(namelist)
}
draw();
}, false);
Another problem is that you cannot just set .src to the name of a file. That would make the request to your server for the file.
To really fix this, just push the file objects to the namelist:
namelist.push(files[i]);
Then as you process them in draw, create localized BLOB urls to show them:
var file = namelist[i];
var url = (window.URL || window.webkitURL).createObjectURL( file );
image.src = url;

It looks like you're using namelist as a global variable. This would be easier (and would avoid needing to empty it at all) if you passed the new array out of the function as a return value.
ie:
function getFiles() {
var newNameList = [];
..... //push entries here.
return newNameList;
}
... and then populate namelist from the return value where you call it:
namelist = getFiles();
However, to answer the question that was actually asked:
Instead of setting the length to zero, you can also reset an array simply by setting it to a new array:
namelist = [];
You haven't shown us how you're 'pushing' entries to the list, but I suspect that the end result is that namelist is being generated as a generic object rather than an array object. If this is the case, then setting .length=0 will simply add a property to the object named length with a value of 0. The length property in the way you're using it only applies to Array objects.
Hope that helps.

If you are using non-numeric indexes then the array will not clear.
"...whenever the length property is changed, every property whose name is an array index whose value is not smaller than the new length is automatically deleted"
Test:
var arr = [];
arr['this'] = 'that';
arr.length = 0;
console.log(arr);
//output ['this':'that']
var arr = [];
arr[0] = 'that';
arr.length = 0;
console.log(arr);
//output []

There is nothing wrong with how you empty the array, so there has to be something else that is wrong with your code.
This works fine, the array doesn't contain the previous items the second time:
var namelist = [];
function draw() {
alert(namelist.join(', '));
}
function getFiles() {
namelist.length = 0; // empty name list
namelist.push('asdf');
namelist.push('qwerty');
namelist.push('123');
draw();
}
getFiles();
getFiles();
Demo: http://jsfiddle.net/Guffa/76RuX/
Edit:
Seeing your actual code, the problem comes from the use of a callback method to populate the array. Every time that you call the function, you will add another event handler, so after you have called the function the seccond time, it will call two event handlers that will each add all the items to the array.
Only add the event handler once.

Related

Advice on the best way to collect values in an array

I need to save all the color values ​​of the elements in the pages of my site and put them in a database. I thought I'd do it this way:
First thing I'm going to pick up the rgb values ​​of each element so
$("*").each(function(e){
createColorArray($(this).css('backgroundColor'));
});
then in the function createColorArray store into an array all the values ​​that are passed
function createColorArray(rgbColor)
{
//Create rgb array
}
and finally remove duplicate items from my array
function removeDoupe(ar) {
var temp = {};
for (var i = 0; i < ar.length; i++)
temp[ar[i]] = true;
var r = [];
for (var k in temp)
r.push(k);
return r;
}
now my question is,
how recommended to create the array? directly inside the $ ("*") or in a dedicated function as I'm thinking? also i need than once removed duplicates in the new array "clean" as well as the rgb value I would have also given the number of times that value was in the original.
Some example code?
As I mentioned in the comments, why not check for duplicates earlier? A simple example:
var colors = [];
$('*').each(function(i, el){
var $element = $(el),
color = $element.css('background-color');
if(!~$.inArray(color, colors))
colors.push(color);
});
console.log(colors);
http://jsfiddle.net/sL9oeywk/
The best way to do this is to do it all while you are working on it. Heres a way you could potentially do it:
var colors = new Array();
var tempColors = {};
$(".colors").each(function(){
var c = $(this).val();
// check if the color exists without looping
if(typeof tempColors[c] == "undefined"){
// if it doesn't, add it to both variables.
tempColors[c] = true;
colors.push(c);
}
});
This will result in two variables: one is an object that you don't have to loop through to find out if you defined it before, one is a colors array that you push to using standard javascript.
You shouldn't make it a dedicated function if you are not reusing it, but you could make it an object like this:
var colors = function(){
var self = this;
self.array = new Array();
// this is a dedicated check function so we don't need separate variables.
// returns true if the color exists, false otherwise
self.check = function(color){
for(var i =0; i < self.array.length; i++){
if(self.array[i] === color) return true;
}
return false;
}
self.add = function(color){
// use the check function, if it returns false, the color does not exist yet.
if(!self.check(color)){
self.array.push(c);
}
}
}
You can then instantiate a colorlist using var colorlist = new colors(); and add colors using colorlist.add("dd0300"). Accessing the array can be done by requesting colorlist.array.

cannot iterate through array and change value in JS

I have to iterate through an array, change one of its values, and create another array refelecting the changes.
this is what I have so far:
JS:
var arr = new Array();
arr['t1'] = "sdfsdf";
arr['t2'] = "sdfsdf";
arr['t3'] = "sdfsdf";
arr['t4'] = "sdfsdf";
arr['t5'] = "sdfsdf";
var last = new Array();
for (var i = 0; i <= 5; i++) {
arr['t2'] = i;
last.push(arr);
}
console.log(last);
Unfortunately, these are my results
As you can see, I am not getting the results needed as 0,1,2.. instead I am getting 2, 2, 2..
This is what i would like my results to be:
How can I fix this?
You have to make a copy, otherwise you are dealing with reference to the same object all the time. As it was said before - javascript does not have associate arrays, only objects with properties.
var arr = {}; // empty object
arr['t1'] = "sdfsdf";
arr['t2'] = "sdfsdf";
arr['t3'] = "sdfsdf";
arr['t4'] = "sdfsdf";
arr['t5'] = "sdfsdf";
var last = new Array();
for (var i = 0; i <= 5; i++) {
var copy = JSON.parse(JSON.stringify(arr)); //create a copy, one of the ways
copy['t2'] = i; // set value of its element
last.push(copy); // push copy into last
}
console.log(last);
ps: you can use dot notation arr.t1 instead of arr['t1']
The array access with ['t2'] is not the problem. This is a regular JavaScript feature.
The problem is: You are adding the SAME array to "last" (5 times in code, 3 times in the screenshot).
Every time you set ['t2'] = i, you will change the values in "last" also, because they are actually just references to the same array-instance.
You must create a copy/clone of the array before you add it to "last".
This is what will happen in all languages where arrays are references to objects (Java, C#...). It would work with C++ STL though.

Javascript two dimensional array initialization

Meet with a really weird javascript problem. See my codes below:
function initBadScripts(controlArray) {
var scriptsLine = prompt("Please enter the bad scripts", "debug");
if (scriptsLine != null) {
var pattern = /;/;
var nameList = scriptsLine.split(pattern);
alert(nameList+" "+nameList.length);
for(var counter = 0; counter < nameList.length; counter++){
controlArray[counter][0]=true;
controlArray[counter][1]= new RegExp(nameList[counter],"g");
alert(controlArray[counter][0]);
}
}
alert("wtf!");
}
var controlArray = [[]];
initBadScripts(controlArray);
I defined a function, and call that function. A 2-dimensional array called 'controlArray' is defined with no value. Basically, the function check the user's input and use regular expression to make a 'namelist'. For example, if the user type in
ExampleOne;ExampleTwo
The function will create an array called 'nameList'
nameList=[ExampleOne,ExampleTwo];
Then I want to make a dynamical initialization of the 2-dimensional array called 'controlArray', according to the length of nameList. However this only works fine the nameList'length is 1. If it exceeds one (the user type in 'ExampleOne;ExampleTwo'), the ExampleTwo does not go into the array, and the
alert("wtf");
doesn't run at all. This seems that there is already an error before it. Any comments?
JavaScript doesn't have a true 2-dimensional array. Rather, you're putting a second array inside the first array. Change it to this:
...
for(var counter = 0; counter < nameList.length; counter++){
controlArray[counter] = [true, new RegExp(nameList[counter],"g")];
...
Yes or you declare your variable like that:
var controlArray = [[],[]];
or
var controlArray = new Array(2);
for (var i = 0; i < 2; i++) {
controlArray[i] = new Array(2);
}

Objects within an Array, to be referenced later

I want to place all the hmAttKeys under one type of hmFeeTypeAttKey so that when I later reference hmAttKeys, it comes out individually but I am not sure of the right sytax. I also tried hmFeeTypeAttKey[0] = [13,3,11,12]. Any suggestions?
hmAttKeys=[]
hmAttKeys[13]="/red";
hmAttKeys[3]="/blue";
hmAttKeys[11]="/green";
hmAttKeys[12]="/yellow";
var hmFeeTypeAttKey = [];
hmFeeTypeAttKey[0] = [13][3][11][12];
hmAttKeys[hmFeeTypeIndex[0]]
hmAttKeys=[]
hmAttKeys[13]="/red";
hmAttKeys[3]="/blue";
hmAttKeys[11]="/green";
hmAttKeys[12]="/yellow";
i=0;
var hmFeeTypeAttKey = [];
for( key in hmAttKeys )
{
hmFeeTypeAttKey[i]=key;
i++;
}
now you can loop through the array to get the keys back for reference..
for(var j=0;j<hmfeeTypeAttKey.length;j++)
{
console.log(hmAttKeys[hmfeeTypeAttKey[j]])
}

How to separate the values from two dimension array in js?

jQuery.get("ChkNewRspLive.php?lastmsgID=" + n, function(newitems){
//some code to separate values of 2d array.
$('#div1').append(msgid);
$('#div2').append(rspid);
});
Let's say the value of newitems is [["320","23"],["310","26"]]
I want to assign "320" and "310" to var msgid.
I want to assign "23" and "26" to var rspid.
How to do that?
I tried to display newitems and the output is "Array". I tried to display newitems[0] and the output is blank.
If I redeclare var newitems = [["320","23"],["310","26"]]; it works. So I guess the variable newitems from jQuery.get is something wrong. Is it I cannot pass the array from other page to current page through jQuery directly?
Regarding the array on other page, if echo json_encode($Arraytest); the output is [["320","23"],["310","26"]] but if echo $Arraytest; the output is Array. How do I pass the array from other page to currently page by jQuery.get?
I don't totally understand the question but I'm going to assume you want the values in an array, as two values can't be stored in one (scalar) variable simultaneously.
jQuery.get("ChkNewRspLive.php?lastmsgID=" + n, function(newitems){
//some code to separate values of 2d array.
var msgid = [],
rspid = [];
for( i = 0 ; i < newitems.length ; i++){
msgid[msgid.length] = newitems[i][0];
rspid[rspid.length] = newitems[i][1];
}
//msgid now contains ["320","310"]
//rspid now contains ["23","26"]
});
Bear in mind those are in the function scope. If you want to use them outside of that scope instantiate them outside. see: closure
You can use pluck from underscore.js: http://documentcloud.github.com/underscore/#pluck
var msgid = _(newitems).pluck(0)
var rspid = _(newitems).pluck(1)
Try this:
function getArrayDimension(arr, dim) {
var res = [];
for(var i = 0; i < arr.length; i++) {
res.push(arr[i][dim]);
}
return res;
}
var newitems = [["320","23"],["310","26"]];
var msgid = getArrayDimension(newitems, 0);
var rspid = getArrayDimension(newitems, 1);
msgid and rspid are arrays holding the 'nth' dimention.
Tnx

Categories