473,406 Members | 2,849 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

Removing Array Elements

I have a final coming up later this week in my beginning Java class and my
prof has decided to give us possible Javascript code we may have to write.
Problem is, we didn't really cover JS and what we covered was within the
last week of the class and all self taught.

Our prof gave us an example of a Java method used to remove elements from an
array:

public void searchProcess()
{ int outIt=0;
for (int tabInd=0; tabInd<tableTwo.size(); tabInd++){
if(tabInd == outIt) {tableTwo.remove(outIt);}
else { outIt=outIt+2;}
}}

and he wants us to write the equivalent code in Js.

Now from what I've found so far, I found the splice() method in Js. But
that's used to add and remove new elements. Is there any way to just remove
elements in an array using a loop?

Ryan
Dec 13 '05 #1
24 4336
RyanTaylor wrote:
[...]
Our prof gave us an example of a Java method used to remove elements from
an array:

public void searchProcess()
{ int outIt=0;
for (int tabInd=0; tabInd<tableTwo.size(); tabInd++){
if(tabInd == outIt) {tableTwo.remove(outIt);}
else { outIt=outIt+2;}
}}

and he wants us to write the equivalent code in Js.
Good luck!
Now from what I've found so far, I found the splice() method in Js. But
that's used to add and remove new elements.
That "and" is not a logical AND :)
Is there any way to just remove elements in an array using a loop?


You can use Array.prototype.pop() where supported to remove
the last element. Use Array.prototype.splice() otherwise.

<URL:http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array >
<URL:http://msdn.microsoft.com/library/en-us/jscript7/html/jsobjarray.asp>

See also

<URL:http://jibbering.com/faq/>
HTH

PointedEars
Dec 13 '05 #2
"RyanTaylor" <Ga**********@cableone.net> writes:
I have a final coming up later this week in my beginning Java class and my
prof has decided to give us possible Javascript code we may have to write.
Problem is, we didn't really cover JS and what we covered was within the
last week of the class and all self taught.
Hmm. Sounds like your professor thinks Javascript is so simple that
you don't need to learn it. Or maybe he does :)
Our prof gave us an example of a Java method used to remove elements from an
array: public void searchProcess()
{ int outIt=0;
for (int tabInd=0; tabInd<tableTwo.size(); tabInd++){
if(tabInd == outIt) {tableTwo.remove(outIt);}
This seems to be working on a List, *not* an array, ...
else { outIt=outIt+2;}
and it removes every third element in a very hard to read way.
Not really code to emulate :)
and he wants us to write the equivalent code in Js.
That'll be bloody hard, since Javascript does not have a List type.
The Javascript array is not a good match.
Now from what I've found so far, I found the splice() method in Js.
That could be used to remove, in the sense of List#remove(int), an
element from an array. However, in Javascript, and in Java as well,
I would prefer building a new list to updating the old one in-place,
especially when the code is this opaque.
But that's used to add and remove new elements.
.... where the number of added elements can be zero,
Is there any way to just remove elements in an array using a loop?


Loops don't remove anything :)
But an array method to remove an element *and* shift all larger
elements down one index ... that would be splice, i.e.,
tableTwo.remove(outIt); // Java
would become
tableTwo.splice(outIt,1); // Javascript

It's still far easier to build a new list!
/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Dec 13 '05 #3

"Lasse Reichstein Nielsen" <lr*@hotpop.com> wrote in message
news:r7**********@hotpop.com...
Hmm. Sounds like your professor thinks Javascript is so simple that
you don't need to learn it. Or maybe he does :)
I'm sure it's simple after you've used it, but I've only been "trying" to
code in Js for a week and a half now. Imagine the following: You know how
to change the oil in your car, the tires, filters, lights, etc. But now you
get a book on how to rebuild an engine, and someone wants it done in a week.
I've seen and coded a bit in Js, but not enough to know how to work this
problem.
This seems to be working on a List, *not* an array, ...
At the end of my post, I've include the full Java code, and it's an
"ArrayList".
and it removes every third element in a very hard to read way.
Not really code to emulate :)
I understand how the Java code works, I just don't know how to translate it
into Js.
That'll be bloody hard, since Javascript does not have a List type.
The Javascript array is not a good match. That could be used to remove, in the sense of List#remove(int), an
element from an array. However, in Javascript, and in Java as well,
I would prefer building a new list to updating the old one in-place,
especially when the code is this opaque. ... where the number of added elements can be zero, Loops don't remove anything :)
But an array method to remove an element *and* shift all larger
elements down one index ... that would be splice, i.e.,
tableTwo.remove(outIt); // Java
would become
tableTwo.splice(outIt,1); // Javascript

It's still far easier to build a new list!
/L


First, the original code:

import java.util.ArrayList;
public class TableValues
{
private ArrayList tableTwo;
public TableValues()
{
tableTwo = new ArrayList();
loadTable();
searchProcess();
printProcess();
}
public void loadTable()
{ tableTwo.add("AB");
tableTwo.add("CD");
tableTwo.add("EF");
tableTwo.add("GH");
tableTwo.add("IJ");
tableTwo.add("KL");
tableTwo.add("MN");
tableTwo.add("OP");
tableTwo.add("QR");
tableTwo.add("ST");
tableTwo.add("UV");
tableTwo.add("WX");
tableTwo.add("YZ");
}
public void searchProcess()
{ int outIt=0;
for(int tabInd=0;tabInd<tableTwo.size();tabInd++){
if(tabInd == outIt){tableTwo.remove(outIt);}
else { outIt=outIt+2;}
}}
public void printProcess()
{ for(int tabInd=0;tabInd<tableTwo.size();tabInd++){
System.out.println(tableTwo.get(tabInd));
}}}

I understand the Java code. loadTable() creates the ArrayList,
searchProcess() removes the element from array[0] skips two, then removes
the next element(3, 5, etc), and printProcess() prints out what's left in
the ArrayList.

Now in respects to Js, I know how to create an Array, I know how to output
the elements of the Array. I'm still stumped though on removing elements.

I did a Google search and found the following:

To remove an individual element of an array, use the delete statement:

delete array[index]

Once an array element has been deleted, any value the element once had is no
longer available. It is as if the element had never been referred to or had
been given a value. The following is an example of deleting elements in an
array:

for (i in frequencies)
delete frequencies[i]

This example removes all the elements from the array frequencies. Once an
element is deleted, a subsequent for statement to scan the array does not
report that element and the in operator to check for the presence of that
element returns zero (i.e., false):

delete foo[4]
if (4 in foo)
print "This will never be printed"

It is important to note that deleting an element is not the same as
assigning it a null value (the empty string, ""). For example:

foo[4] = ""
if (4 in foo)
print "This is printed, even though foo[4] is empty"
(from http://www.delorie.com/gnu/docs/gawk/gawk_125.html)

Now I tried using the above in some simple code, and the screen go blank as
soon as I run the code:

<html>
<body>

<script type="text/javascript">
var mycars = new Array()
mycars[0] = "Saab"
mycars[1] = "Volvo"
mycars[2] = "BMW"
mycars[3] = "Ford"
mycars[4] = "Forda"
mycars[5] = "Fordb"
mycars[6] = "Fordc"
mycars[7] = "Fordd"
mycars[8] = "Forde"
mycars[9] = "Fordf"
mycars[10] = "Fordg"
mycars[11] = "Fordh"
mycars[12] = "Fordi"

for (outInt=0;tabInd=0;tabInd<mycars.length;tabInd++)
{
if (tabInd==outInt)
{
delete mycars(outInt)
}
else
{
outInt=outInt+2
}
}

for (i=0;i<mycars.length;i++)
{
document.write(mycars[i] + "<br />")
}
</script>

</body>
</html>

What's missing?

Thanks for any help,

Ryan
Dec 14 '05 #4
VK
Your JavaScript code doesn't work for the same reason why the Java
source will never work. That must be a "sh** level check" assignment
(will you see the gotcha or not). Another even more possible
possibility is that your prof has no clue neither about Java nor about
JavaScript. That happens left and right too.

Why this algorithm cannot be implemented? Because it dynamically checks
a dynamic property but treats it as a local constant. Each
tableTwo.remove() decreases the amount of elements therefore
tableTwo.size() decreases. But on each loop you read it as never
nothing happened. This leads to a dead lock or for at least to the
results you did not expect.

As commenting on the prof's knowledge may lead you to a strong "D" in
the next semester ;-) we are leaving Java out. And for JavaScript part
you have to use the already proposed way with *new array* where you
store removed elements.

This is also the only proper way to work with *array* (not a hash or
collection).

Dec 14 '05 #5
RyanTaylor wrote:
"Lasse Reichstein Nielsen" <lr*@hotpop.com> wrote [...]:
[...]
But an array method to remove an element *and* shift all larger
elements down one index ... that would be splice, i.e.,
tableTwo.remove(outIt); // Java
would become
tableTwo.splice(outIt,1); // Javascript

It's still far easier to build a new list! ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [...]
[...]
Now in respects to Js, I know how to create an Array, I know how to output
the elements of the Array. I'm still stumped though on removing elements.

I did a Google search and found the following:

To remove an individual element of an array, use the delete statement:

delete array[index]

Once an array element has been deleted, any value the element once had is
no longer available. It is as if the element had never been referred to or
had been given a value.


True.
The following is an example of deleting elements in an array: for (i in frequencies)
delete frequencies[i]

This example removes all the elements from the array frequencies.
Yes, but

frequencies = new Array();

is faster and less error-prone :)
Once an
element is deleted, a subsequent for statement to scan the array does not
report that element and the in operator to check for the presence of that
element returns zero (i.e., false):

delete foo[4]
if (4 in foo)
print "This will never be printed"
I doubt you found a a J(ava)Script/ECMAScript tutorial. AFAIK there is
no `print' statement there, and if `print' would be a method, the Call
Operator () is missing.
It is important to note that deleting an element is not the same as
assigning it a null value (the empty string, ""). For example:

foo[4] = ""
if (4 in foo)
print "This is printed, even though foo[4] is empty"
(from http://www.delorie.com/gnu/docs/gawk/gawk_125.html)
Ahh, it is about gawk (GNU awk). You see? Do not mix languages :)
[...]
var mycars = new Array()
mycars[0] = "Saab"
mycars[1] = "Volvo"
mycars[2] = "BMW"
mycars[3] = "Ford"
mycars[4] = "Forda"
mycars[5] = "Fordb"
mycars[6] = "Fordc"
mycars[7] = "Fordd"
mycars[8] = "Forde"
mycars[9] = "Fordf"
mycars[10] = "Fordg"
mycars[11] = "Fordh"
mycars[12] = "Fordi"
var mycars = new Array("Saab", "Volvo", "BMW", "Ford", "Forda", "Fordb",
"Fordc", "Fordd", "Forde", "Fordf", "Fordg", "Fordh", "Fordi");

or (ECMAScript 3 compliant)

var mycars = ["Saab", "Volvo", "BMW", "Ford", "Forda", "Fordb", "Fordc",
"Fordd", "Forde", "Fordf", "Fordg", "Fordh", "Fordi"];
for (outInt=0;tabInd=0;tabInd<mycars.length;tabInd++) [1]^^^^^^ ^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^[4]
[2] [3]

[1] the `var' keyword are missing, those are globals
[2] causes a syntax error at [4], proper syntax is

for (init; loop-cond; inc-expr)

[3] inefficient
{
if (tabInd==outInt)
{
delete mycars(outInt)
}
else
{
outInt=outInt+2
}
}
Eeek. Care to indent code?

for (var outInt = tabInd = 0, len = mycars.length; tabInd < len; tabInd++)
{
if (tabInd == outInt)
{
delete mycars(outInt);
}
else
{
outInt += 2;
}
}
for (i=0;i<mycars.length;i++)
Same here.
{
document.write(mycars[i] + "<br />") ^
IE does not support XHTML.
What's missing?


Proper syntax. <URL:http://jibbering.com/faq/#FAQ4_43>
PointedEars
Dec 14 '05 #6
VK

VK wrote:
Your JavaScript code doesn't work for the same reason why the Java
source will never work. That must be a "sh** level check" assignment
(will you see the gotcha or not). Another even more possible
possibility is that your prof has no clue neither about Java nor about
JavaScript. That happens left and right too.


Also the quoted way from the previous post (using "delete") shows as
well how many clueless people are posting wrong advises in the
Internet.

"delete" as well as "for (prop in obj)" loop have nothing to do with
arrays. They are used to respectively delete and enumerate object
properties.

If Java notation is closer to you then:
delete myArray[i]
is something like pseudo-Java:
delete(((Object)myArray).(i.toString()))
// casting myArray back into Object object
// and index value into string property name

As you can see it has *nothing* to do with manipulating array per se.
For myArray *being an array* it is just a 3rd (subnatural) force so it
doesn't notice disappearing elements and it doesn't update length
property.
Only on the next loop it will discover that somehow some of its
elements got undefined value: elm1,undefined, elm2, etc. It is easy to
check.

I encourage you to read
<http://www.geocities.com/schools_ring/ArrayAndHash.html> to have a
clear picture what are you dealing with.

P.S. delete "failure" (which is not really a failure but expected
behavior) closes the question completely: you have to use an
intermediary array for the proposed task: both in Java and JavaScript.
I would guess that using some extended features of Java you can create
a working (though very ineffective) solution corresponding to your
prof's ideas of programming. JavaScript is more strict: either you need
array and its methods or your need something else (and other methods).

P.P.S. Few more questions about arrays and someone will get their
Christmas e-shop after Christmas. I'm like a dog over pissed tree -
just cannot go over array issues :-(
:-)

Dec 14 '05 #7
"VK" <sc**********@yahoo.com> writes:
Why this algorithm cannot be implemented? Because it dynamically checks
a dynamic property but treats it as a local constant. Each
tableTwo.remove() decreases the amount of elements therefore
tableTwo.size() decreases. But on each loop you read it as never
nothing happened. This leads to a dead lock or for at least to the
results you did not expect.


I don't see the problem, nor how anything is treated as a constant.

Each time through the loop increments tabInd and might decrement the
size of tableTwo. It then checks whether tabInd is less than
tableTwo.size(), which uses the new value of it (as it should be, since
otherwise you *would* be able to get IndexOutOfRange exceptions).

In effect, the loop alternates between removing an element and
increasing outIt by 2, each time increasing tabInd by 1 (which
is why tabInd == outIt every second step).

It will terminate, with every third element of the oringinal list
removed, starting with index 0.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Dec 15 '05 #8
"VK" <sc**********@yahoo.com> writes:
Also the quoted way from the previous post (using "delete") shows as
well how many clueless people are posting wrong advises in the
Internet.
Hear, hear.
"delete" as well as "for (prop in obj)" loop have nothing to do with
arrays.
And this is an example. Both are perfectly usable with arrays.
They are used to respectively delete and enumerate object
properties.
And all array elements are also object properties. The arrayness
is an abstraction on top of an object, but nothing prevents you
from using basic object operations on arrays as well. And in some
cases, they are just what you need.
If Java notation is closer to you then:
delete myArray[i]
is something like pseudo-Java:
delete(((Object)myArray).(i.toString()))
// casting myArray back into Object object
// and index value into string property name
This makes no sense as Java, where objects properties are not
dynamically assignable or deleteable.

A close match would be that arrays are really implemented using a Map
with String keys. All accesses using integers are converted to map
operations using a String representation of the number.

You can still use Map methods directly. You will be breaking the
abstraction, which is really jut a point of view, and not enforced by
the language in any way, but if you know what you are doing, it might
be exactly the right thing to do.

It's pretty much the problem with Properties in Java. They are exposing
that they are Hashtable's, so you can break the abstraction of them
being String-to-String mappings. It might not be stellar desing, but
it still works.
As you can see it has *nothing* to do with manipulating array per se.
Arrays are objects. You can choose not to see them as such, and keep
the abstraction, but that does not make them be less of an object
to the language.
I encourage you to read
<http://www.geocities.com/schools_ring/ArrayAndHash.html> to have a
clear picture what are you dealing with.


This is an old discussion, and there is *not* agreement that the
position presented at that page is a advantageous way of percieving
javascript arrays.
/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Dec 15 '05 #9
Thomas 'PointedEars' Lahn <Po*********@web.de> writes:
for (var outInt = tabInd = 0, len = mycars.length; tabInd < len; tabInd++)
{
if (tabInd == outInt)
{
delete mycars(outInt); Should be:
delete mycars[outInt];
to be correct syntax. }
else
{
outInt += 2;
}
}


This is a properly syntax checked version of the algorithm RyanTaylor
posted. However, it is not the same algorithm as the original Java
method.

This Javascript method deletes every other element, but deletion merely
leaves an empty position in the array. It doesn't shift the remaining
elements down, and doesn't decrease the length of the array.

The original Java version did this, and therefore only removed every
third element.

If the
delete mycars[outInt];
was changed to
mycars.splice(outInt,1);
then the algorithm would be equivalent to the Java version.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Dec 15 '05 #10
VK

Lasse Reichstein Nielsen wrote:
"VK" <sc**********@yahoo.com> writes:
Why this algorithm cannot be implemented? Because it dynamically checks
a dynamic property but treats it as a local constant. Each
tableTwo.remove() decreases the amount of elements therefore
tableTwo.size() decreases. But on each loop you read it as never
nothing happened. This leads to a dead lock or for at least to the
results you did not expect.


I don't see the problem, nor how anything is treated as a constant.

Each time through the loop increments tabInd and might decrement the
size of tableTwo. It then checks whether tabInd is less than
tableTwo.size(), which uses the new value of it (as it should be, since
otherwise you *would* be able to get IndexOutOfRange exceptions).

In effect, the loop alternates between removing an element and
increasing outIt by 2, each time increasing tabInd by 1 (which
is why tabInd == outIt every second step).

It will terminate, with every third element of the oringinal list
removed, starting with index 0.


You are right: I did not have Java IDE handy, and I misread the stream
by my eyes.
This assignment is using (rather weirdly) the dinamic nature of Vector
and swinged stuff based on it (like ArrayList).

JavaScript array is sparse plus it is a real *array* so this trick will
not fly.

To save the good name of JavaScript :-) OP may use another
JavaScript-specific trick by overloading array. This allows to formally
stay within the provided array only:

<script type="text/javascript">

/* Remove each 3rd element from tableTwo */

var killer = 3;

var tableTwo = [
"AB","CD","EF",
"GH","IJ","KL",
"MN","OP","QR",
"ST","UV","WX",
"YZ"
];

var len = tableTwo.length;

// Overload array:
tableTwo.tmp = [];

for (i=0; i<len; i++) {
if (i%killer) {
tableTwo.tmp.push(tableTwo[i]);
}
}

// Normalize array:
tableTwo = tableTwo.tmp;

alert(tableTwo);

/* School profs are bored dorks as usual :-) */
</script>

Dec 15 '05 #11

"VK" <sc**********@yahoo.com> wrote in message
news:11*********************@g43g2000cwa.googlegro ups.com...
Your JavaScript code doesn't work for the same reason why the Java
source will never work. That must be a "sh** level check" assignment
(will you see the gotcha or not). Another even more possible
possibility is that your prof has no clue neither about Java nor about
JavaScript. That happens left and right too.
Hard to know. Our Prof really hasn't "taught" us anything this semester.
We've been using the book "Objects First With Java: A Pratical Introduction
Using BlueJ (2nd Ed.)". His lecture consisted of us going through each
chapter, working on the exercises while he "dinked" around on the computer.
Yes he graded our "projects" and test, but hard to really know what his
knowledge of the languages are.

I had emailed him asking for help with how to delete elements from an array
in Js, and here's his response:

"Because Javascript does not have an ArrayList object a remove method
is not not available. To remove something from an array you move everything
up one position from the deletion point. A much more code intensive
process."

Now I would expect a response like that if we had been coding in Js all
semester, but once again...he thrust Js upon us the last week, and thrust
the problem we've been discussing last Friday. Plus the "help" he gave us
was the following website: http://www.w3schools.com . A good website that
I can tell for the basics, but as you can probably tell, I needed a bit more
guidence.
As commenting on the prof's knowledge may lead you to a strong "D" in
the next semester ;-) we are leaving Java out. And for JavaScript part
you have to use the already proposed way with *new array* where you
store removed elements.

Let's hope not...after my final tomorrow, I'm done with his Java class.
Though I do have a class with him next semester regarding "hardware". But
I've always been better with hardware, and I know what to expect in his
class.

Lastly, thanks for all the help. You, Lasse, and Thomas helped me out a
bunch!

Ryan
Dec 15 '05 #12

"Thomas 'PointedEars' Lahn" <Po*********@web.de> wrote in message
news:20****************@PointedEars.de...
Ahh, it is about gawk (GNU awk). You see? Do not mix languages :)
"Now I see," said the blind man ;). I did not realize that awk was a
language :).
Eeek. Care to indent code?


Sorry about that Thomas. When I "code", I first get the code to work, then
clean it up (add comments, indent, etc). I hope I didn't make you go blind
;).

Thank you so much for helping with my "code". It really helped me out of a
bind. Let's just hope that the question he asks about removing elements
from an array is worth more than just 5 or 10 points.

Ryan
Dec 15 '05 #13
"Lasse Reichstein Nielsen" <lr*@hotpop.com> wrote in message
news:ve**********@hotpop.com...
If the
delete mycars[outInt];
was changed to
mycars.splice(outInt,1);
then the algorithm would be equivalent to the Java version.

/L


I plugged that in, and it worked like a gem. Thank you so much Lasse, I
really appreciate all the help.

Ryan
Dec 15 '05 #14
VK

Lasse Reichstein Nielsen wrote:
"VK" <sc**********@yahoo.com> writes:
I encourage you to read
<http://www.geocities.com/schools_ring/ArrayAndHash.html> to have a
clear picture what are you dealing with.


This is an old discussion, and there is *not* agreement that the
position presented at that page is a advantageous way of percieving
javascript arrays.


This article gives an logical explanation why arrayObject['foo'] =
'bar' doesn't change arrayObject.length
Other sources don't.

This article gives an logical explanation why delete arrayObject[i]
doesn't change arrayObject.length and what happens with arrayObject[i]
element.
Other sources don't.

This article gives an logical explanation why above index 4294967294
arrayObject doesn't behave as expected *from array*.
Other sources don't.

This article explanes slice() and splice() methods behavior in sparse
array.
Other sources don't.

We can have an academical discussion as long as we want. But in
practical programming the only theory has a value which gives answers
corresponding to the reality (execution results).
And later the Occam's' raisor comes on help: if something explains the
fact in the best way then it must be the most correct explanation and
no extra is needed.

Array object is an Object object (plus autoupdated length property) :
this explanation leads to countless glitches with the reality, like the
one above.

Array object extends Object object (like any other object) but it's
all different entity etc. by
<http://www.geocities.com/schools_ring/ArrayAndHash.html> and your
results will always correspond to the reality.

Mind for the raisor? ;-)

Dec 15 '05 #15
On 15/12/2005 09:37, VK wrote:

[<http://www.geocities.com/schools_ring/ArrayAndHash.html>]
This article gives an logical explanation why arrayObject['foo'] =
'bar' doesn't change arrayObject.length
No it doesn't.

It reminds a two-story house with separate exits. The word
separate is very important here, because arrayObject knows
nothing about it's other hash side, so does not its hash side
about array. Kind of objective schizophrenia...

That is not an explanation, but something quite random that you dreamt
up. Worse than that, what it goes on to say is entirely wrong:

So if you occasionally do:
arrayObject[stringValue] = value;
no error will be shown. arrayObject will get new property
stringValue (new stringValue:value hash pair). But it will
neither be counted into arrayObject.length nor it will
processed by array methods.

as demonstrated by:

var index = '0', /* A string value */
array = []; /* An array */

/* array.length is currently zero (0). */
array[index] = 'value';
/* array.length is now one (1). */

Not at all what you wrote would happen.

The correct explanation is that a property name (which is always a
string) is only considered to be an array index if the following
comparisons evaluate to true:

ToString(ToUint32(propertyName)) === propertyName

ToUint32(propertyName) < 2^32 - 1

All other property names will be considered to be simple property names
and will not treated specially by the internal [[Put]] method of Array
objects.
Other sources don't.
The Google groups archive does, as does ECMA-262.
This article gives an logical explanation why delete arrayObject[i]
doesn't change arrayObject.length and what happens with arrayObject[i]
element.
No it doesn't. It doesn't mention what occurs when the delete operator
is used with Array objects at all. It doesn't even state what happens
when it is used with other objects.
Other sources don't.
As above.
This article gives an logical explanation why above index 4294967294
arrayObject doesn't behave as expected *from array*.
By which I assume you mean:

What is the biggest possible index value? The ECMAScript
standard for JavaScript allows 4294967295 array elements per
array — that's one less than 32 bits can hold. The remaining
one is used for the length value.

That doesn't explain what happens when an out-of-range index is used. It
doesn't even clearly answer the question it poses at the start.
Other sources don't.
As above. The explanation for what is considered an array index is also
a sufficient explanation in itself.
This article explanes slice() and splice() methods behavior in sparse
array. [...]
It doesn't mention what the Array.prototype.splice method does at all,
and only provides a vague demonstration of the slice method. Neither
needs any special explanation, anyway. As with other Array.prototype
methods, they act only on properties that are considered array indices,
and that subset within the range [0,length).
We can have an academical discussion as long as we want. But in
practical programming the only theory has a value which gives answers
corresponding to the reality (execution results).
What you consistently fail to accept is that the theory does, in the
overwhelming majority of cases, agree with the empirical results.

When considering Arrays, about the only issue is that many browser
implementations of methods that return arrays (slice, reverse, etc.)
will copy all elements. That is, the reference algorithm steps that
state "If this object does not have a property named by ..." are ignored.
And later the Occam's' raisor comes on help: if something explains the
fact in the best way then it must be the most correct explanation and
no extra is needed.


That is not what Occam's _Razor_ states, nor does it apply here; your
'theories' are not equally predictive.

[snip]

For the good of impressionable newcomers (and the tolerance of regulars)
please stop pretending that you understand this subject.

Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Dec 15 '05 #16
VK

RyanTaylor wrote:
Thank you so much for helping with my "code". It really helped me out of a
bind. Let's just hope that the question he asks about removing elements
from an array is worth more than just 5 or 10 points.


OK... It seems that the e-store will be done on time (surprising
myself) so I have some more time :-)

I guess that OP has already passed his test (how much did you get?) but
if anyone will read this thread later:

The original assignment as proposed
<http://groups.google.com/group/comp.lang.javascript/browse_frm/thread/35de2906e10ebf70/dedb51d260203d2f#dedb51d260203d2f>

contained five(!) rather rude errors made by professor:

1) Java ArrayList is a kind of Array.
2) It's a kind of array but more effective than conventional array
3) JavaScript is a stripped down version of Java
4) "delete" operator is applicable to arrays.
5) In JavaScript you have to emulate ArrayList by using less effective
methods of the conventional JavaScript Array.
....
1) Java "ArrayList" is not a kind of Array.
It is a Swing derivate of the groung-Java "Vector". And the Vector is
the development of the prehistoric but still used groung-Java FIFO
"Stack". So yes both Array and ArrayList are data structures, but they
have whole different evolution chains.

2) Vector > ArrayList is very resource-expensive beast because i) it
stores all elements as objects (no primitives) and ii) it dynamically
rearrange all elements in the memory on each remove. The simplicity of
its usage should not be misleading from the complexity of the process.
On an averagely small amount of primitive values array is much more
effective.

3) JavaScript is not stripped down version of Java.

4) As it was explained in this thread "delete" operator has nothing to
do with Array.

5) JavaScript itself doesn't have and it doesn't use Vector data types.
But - surprise, surprise! - some DOM objects do use Vector-like data
structures. One of them is form SELECT object. So if - despite the
point 2 above - one still wants a Vector and just cannot live w/o it,
then:

<html>
<head>
<title>ArrayList</title>
<meta http-equiv="Content-Type" content="text/html;
charset=iso-8859-1">
<script type="text/javascript">

function foo() {
var ArrayList = document.createElement('SELECT');
with (ArrayList) {
options[0] = new Option('kill');
options[1] = new Option('leave');
options[2] = new Option('leave');
options[3] = new Option('kill');
options[4] = new Option('leave');
options[5] = new Option('leave');
options[6] = new Option('kill');
options[7] = new Option('leave');
options[8] = new Option('leave');
options[9] = new Option('kill');
}

var outIt = 0;
for(var tabInd=0; tabInd<ArrayList.length; tabInd++){
if (tabInd == outIt) {
ArrayList.options[outIt] = null;
}
else {
outIt+=2;
}
}
//for (i=0; i<ArrayList.length; i++) {
// alert(ArrayList.options[i].text);
//}
}

</script>
</head>

<body onload="foo()">

</body>
</html>

Dec 16 '05 #17
VK
VK wrote:
groung-Java


* ground-Java * of course, so do not look this term in the Wiki :-)
A good sample of how typos miltiply grace to copy'n'paste

Dec 16 '05 #18
In article <11*********************@g14g2000cwa.googlegroups. com>, VK
<sc**********@yahoo.com> writes

<snip>
1) Java "ArrayList" is not a kind of Array.
It is a Swing derivate of the groung-Java "Vector". And the Vector is
the development of the prehistoric but still used groung-Java FIFO
"Stack". So yes both Array and ArrayList are data structures, but they
have whole different evolution chains.
You loud-mouthed twit. Are you deliberately spreading misinformation?

The Java class is called ArrayList because its objects use Java Arrays
to implement the List interface. The List interface allows indexed
access just as arrays do, so it *is* a 'kind of' array.

It has nothing to do with Swing and it isn't derived from Vector or
Stack. It's a different utility class.

Array is a set of primitive types; ArrayList has a user-defined class
definition.
2) Vector > ArrayList is very resource-expensive beast because i) it
stores all elements as objects (no primitives) and ii) it dynamically
rearrange all elements in the memory on each remove. The simplicity of
its usage should not be misleading from the complexity of the process.
On an averagely small amount of primitive values array is much more
effective.

<snip>

The Java library has several container types because each is efficient
at certain operations and not so good at others. A clear-thinking
designer will choose the type that's most appropriate for the
application. But not VK I suspect.

John
--
John Harris
Dec 16 '05 #19
VK

John G Harris wrote:
The Java class is called ArrayList because its objects use Java Arrays
to implement the List interface. The List interface allows indexed
access just as arrays do, so it *is* a 'kind of' array.
<http://java.sun.com/j2se/1.4.2/docs/api/java/util/ArrayList.html>
<quote>
This class is roughly equivalent to Vector, except that it is
unsynchronized
</quote>

I will skip on quoting all Java docs or telling you the programming
evolution story. You need to know it, otherwise it will take too many
posts to deliver. Plus clj is not a course-based remote learning
center.
You loud-mouthed twit. Are you deliberately spreading misinformation?


Love you too.
Your assignment for before Chrismas:
1) study relevant Java classes from Java 1.0 till now. Stack, Vector,
ArrayList - time of appearance, properties, properties evolution.
2) find the cardinal difference between Vector-family and Array-family
(hint: watch the heap mechanics)

Submit the results into this thread in free-form by December 30.

(5 points)

Dec 16 '05 #20
"VK" <sc**********@yahoo.com> writes:
1) Java "ArrayList" is not a kind of Array.
It is a Swing derivate of the groung-Java "Vector".
ArrayList is not related to Swing at all. While the Collections
framework was added at the same time as Swing, they are unrelated.

The Collections framework aws added in Java version 1.2 (IIRC), and
the existing data structures (Hashtable and Vector) were retrofitted
to match the new interfaces (Map and List). They were still
synchronized, as opposed to the newer HashMap and ArrayList, and
still supported their old method names and Enumerator's (in addition
to the new Iterator's)
And the Vector is the development of the prehistoric but still used
groung-Java FIFO "Stack".


I don't understand what "development" means here. Stack extends
Vector, which is generally considered at bad design, even by the
designer themselves.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Dec 17 '05 #21
VK

Lasse Reichstein Nielsen wrote:
"VK" <sc**********@yahoo.com> writes:
1) Java "ArrayList" is not a kind of Array.
It is a Swing derivate of the groung-Java "Vector".


ArrayList is not related to Swing at all. While the Collections
framework was added at the same time as Swing, they are unrelated.


They are. But the full definition of "Swing" (as build-up over the
ground-Java) is better discussed in comp.lang.java.* groups. I'm ready
to meet you in any of them in January where guru's like Roedy Green
will squeeze stuff out ot *my* poor body. Still I'm still ready to meet
you in any of them by your choice.
And the Vector is the development of the prehistoric but still used
groung-Java FIFO "Stack".


I don't understand what "development" means here. Stack extends
Vector, which is generally considered at bad design, even by the
designer themselves.


Development == Evolution (as opposed to degradation). Therefore Stack
*cannot* extend Vector as Tiranozaurus Rex cannot be a child of monkey.

I'll be back with more later, as well as Michael Winter valuable
comments in this thread are not neglected at all.
Just 1,700 (what a crap and why so many?!) French purses "Christmas
collection" mangement takes all my mental forces right now. I can just
get a rest by answering simple question and kicking Ears' a** for
relaxation. :-) But I'll be back :-)

Dec 17 '05 #22
In article <11*********************@g49g2000cwa.googlegroups. com>, VK
<sc**********@yahoo.com> writes

<snip>
or telling you the programming
evolution story. You need to know it, <snip>1) study relevant Java classes from Java 1.0 till now. Stack, Vector,
ArrayList - time of appearance, properties, properties evolution.
The behaviour of ArrayList objects is determined by the relevant class
definitions, supplemented by documentation where the definitions aren't
released, and by nothing else. At all. Whatsoever.

The behaviour is not affected by the phase of the moon, the reasons for
inventing the class, the date it was invented, the date it was released,
or even by your opinions.

2) find the cardinal difference between Vector-family and Array-family
(hint: watch the heap mechanics)

<snip>

One is a set of primitive types, the other isn't. Heap mechanics are
hidden from programmers.

John
--
John Harris
Dec 17 '05 #23
On 15/12/2005 16:19, Michael Winter wrote:

[snip]
ToString(ToUint32(propertyName)) === propertyName

ToUint32(propertyName) < 2^32 - 1

All other property names will be considered to be simple property names
and will not treated specially by the internal [[Put]] method of Array
objects.


With the exception of length, of course.

[snip]

Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Dec 17 '05 #24
RyanTaylor wrote:
<snip>
Sorry about that Thomas. When I "code", I first get the code to work, then
clean it up (add comments, indent, etc). I hope I didn't make you go blind
;).

<snip>

I'm surprised you don't find it easier to debug your code if it's
indented in the first place.

Stewart.

--
-----BEGIN GEEK CODE BLOCK-----
Version: 3.1
GCS/M d- s:- C++@ a->--- UB@ P+ L E@ W++@ N+++ o K-@ w++@ O? M V? PS-
PE- Y? PGP- t- 5? X? R b DI? D G e++>++++ h-- r-- !y
------END GEEK CODE BLOCK------

My e-mail is valid but not my primary mailbox. Please keep replies on
the 'group where everyone may benefit.
Dec 20 '05 #25

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: D. Alvarado | last post by:
Hello, I have an array that contains numbers. Each element in the array is guaranteed to be unique. Let's say I have another variable which I know for certain is in the array, but I don't know...
5
by: effendi | last post by:
I wrote a simple script to remove an element of an array but I don't think this is the best way to go about it. I have a list of about five elements seperated by ";" I split the array using...
2
by: bmgz | last post by:
I have written a simple function that validates a form based on the form objects' className attribute. The form basically write a "field required" message next to the form element that is blank(and...
7
by: Adam Honek | last post by:
Is there a direct way to remove one entry from a one dimensional array? I keep looking but either my eyes are funny or it isn't there. Must we really create a temp array and copy all but 1 of...
6
by: Niyazi | last post by:
Hi all, What is fastest way removing duplicated value from string array using vb.net? Here is what currently I am doing but the the array contains over 16000 items. And it just do it in 10 or...
7
by: vsgdp | last post by:
I have a container of pointers. It is possible for two pointers to point to the same element. I want to remove duplicates. I am open to which container is best for this. I thought of using...
1
by: =?Utf-8?B?ai5hLiBoYXJyaW1hbg==?= | last post by:
Hello, I've eliminated the bulk of code, this should be sufficient: byte fromEncrypt; string sDecryptedString; //Read the data out of the crypto stream. csDecrypt.Read(fromEncrypt, 0,...
2
by: kardon33 | last post by:
What I need to do is take a multi dimensional array and delete all elements with the word "Total" in . I think i would use array_filter but dont know exactly how. Could some one please help me. ...
10
by: arnuld | last post by:
WANTED: /* C++ Primer - 4/e * * Exercise: 9.26 * STATEMENT * Using the following definition of ia, copy ia into a vector and into a list. Use the single iterator form of erase to...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.