Online Documentation Server
 ПОИСК
ods.com.ua Web
 КАТЕГОРИИ
Home
Programming
Net technology
Unixes
Security
RFC, HOWTO
Web technology
Data bases
Other docs

 


 ПОДПИСКА

 О КОПИРАЙТАХ
Вся предоставленная на этом сервере информация собрана нами из разных источников. Если Вам кажется, что публикация каких-то документов нарушает чьи-либо авторские права, сообщите нам об этом.




Previous Table of Contents Next

Sometimes you want to refer to all elements of a uniform-type array. The following method is designed to be a prototype of the Array object, returning an array of element subscripts where the specified value has been found. Here is the method:

function getSubscripts(type) {
  var ar = new Array()
  var arSub = 0
  for (var i = 0; i < this.length; ++i) {
 if (typeof this[i] == type) {
ar[arSub] = this[i]
++arSub
 }
  }
  return ar
}

Array.prototype.getSubscripts = getSubscripts

You can use the preceding prototype with arrays. For example:

var ar1 = new Array(6)
ar1[1] = 5
ar1[2] = 7
ar1[3] = "a"
ar1[4] = 2
ar1[5] = "b"
var ar1Temp = ar1.getSubscripts("number")
alert("There are " + ar1Temp.length + " numeric values in ar1") // 3
alert("The third number of ar1 is " + ar1Temp[2]) // 2
alert(ar1Temp) // 5, 7, 2 (discussed later in this chapter!)

This method returns an array. You can refer directly to the returned array:

var ar1 = new Array(6)
ar1[1] = 5
ar1[2] = 7
ar1[3] = "a"
ar1[4] = 2
ar1[5] = "b"
alert("The third number of ar1 is " + ar1.getSubscripts("number")[2])

Strings in JavaScript are String objects, not arrays. There are many useful methods that operate only on strings, so dealing with strings as arrays of characters, as is often the practice in other languages, is useless and almost impossible.

If you try to print an array, you will see that JavaScript prints the values of all elements in consecutive order, with a delimiting comma in between. You can use a user-defined prototype method to return a string containing all values delimited by a user-provided string:

function getList(str) {
  var text = ""
  for (var i = 0; i < this.length – 1; ++i) {
 text += this[i] + str
  }
  text += this[this.length – 1]
  return text
}

Array.prototype.getList = getList

var ar = new Array(5)
ar[1] = 3
ar[3] = "a"
ar[4] = "b b b"
document.write(ar.getList(" ; ")) // null ; 3 ; null ; a ; b b b

Notice that the loop in the method executes until i < this.length – 1. The reason is that the loop concatenates the delimiter (the method’s parameter) after each element of the array. We do not want one placed after the last element, so the last element is concatenated to the accumulated string after the loop terminates.

Array Properties

Although you can add your own properties to the Array object, not all tasks can be achieved by high-level programming via JavaScript. The only built-in property of the Array object is length. When you create an instance of an object (an array), the number of properties (elements) is stored in the length property. You can refer to it as a regular property. We have already seen this property in action earlier in this chapter.

Let’s say you want to display some messages, one after the other. You should use an array to store the messages:

var messages = new Array()
messages[0] = "message 1"
messages[1] = "message 2"
messages[2] = "message 3"

You can then use a loop to display the messages successively:

for (var i = 0; i < messages.length; i++) {
   document.write(messages[i] + "<BR>")
}

The length property can also be modified; that is, you can change the length of the array by assigning the property a value. Here is an example:

var ar = new Array(6)
ar[0] = "Mouse"
ar[1] = 8
ar[2] = 18
ar[3] = true
ar[4] = "Dog"
ar[5] = "Cat"
ar.length = 3
alert(ar[2]) // 18
alert(ar[3]) // null

The array consisting of six elements was reduced to three. The last three values were chopped off. Be extra careful when you reduce the size of an array because shifted-off values are unrecoverable.

Array Methods

In this section we will deal with many array methods. We will simulate some array functions in Perl using prototype methods. JavaScript features three built-in methods which we shall also discuss:

  • join()
  • reverse()
  • sort()

In this section we use the getList prototype method, introduced in the section “Array Types,” to print arrays.

chop()

The chop method chops off the last character of all strings that are elements of an array. Here it is:

function chop() {
  for (var i in this) {
 if (typeof this[i] == "string")
this[i] = this[i].substring(0, this[i].length – 1)
 }
  }

Array.prototype.chop = chop

// EXAMPLE
////////////////////////////////////////////

var line = new Array("red", "green", "blue")
line.chop()
document.write(line.getList(" "))

The script’s output is:

re gree blu

The general syntax is:

arrayInstance.chop()

The substring() method is explained in Chapter 16, Handling Strings.

grep()

The grep method evaluates the expression (expr) for each element of the array. It returns another array consisting of those elements for which the expression evaluated to true (the pattern was matched). To understand this method you should know that if string2 is found in string1, string1.indexOf(string2) is not equal to –1. Here is the method:

function grep(str) {
  var ar = new Array()
  var arSub = 0
  for (var i in this) {
 if (typeof this[i] == "string" && this[i].indexOf(str) != –1) {
ar[arSub] = this[i]
arSub++
 }
  }
  return ar
}

Array.prototype.grep = grep

// EXAMPLE
////////////////////////////////////////////

var line = new Array("mask", "Mascot", "mine", "amass", "hot")
document.write(line.grep("mas").getList(" "))
document.write("<BR>")
document.write(line.grep("mas").length)

The output of this script is:

mask amass
2

The general syntax is:

arrayInstance.grep(expr)

Previous Table of Contents Next


With any suggestions or questions please feel free to contact us