javascript高级程序设计学习笔记-Chapter 5: Reference Types

1.The Object Type(Object类型)

There are two ways to explicitly create an instance of Object. The first is to use the new operator with the Object constructor like this:

var person = new Object();
person.name = "Nicholas";
person.age = 29;

The other way is to use object literal notation(对象描述符号):

var person = {
    name : "Nicholas",
    age : 29
};

也可以两种结合使用:

var person = {};               
person.name = "Nicholas";
person.age = 29;

2.THE ARRAY TYPE(数组类型)

An ECMAScript array is very different from arrays in most other programming languages. As in other languages, ECMAScript arrays are ordered lists of data, but unlike in other languages, they can hold any typeof data in each slot. This means that it’s possible to create an array that has a string in the first position, a number in the second, an object in the third, and so on. ECMAScript arrays are also dynamically sized, automatically growing to accommodate any data that is added to them.

(javascript中的数组与其他语言的数据很不一样,一个数组中可以存在不同类型的数值,比如,第一个数值是字符串,第二个数值可以是数字型,第三个数值可以使对象。并且在javascript中,数组的大小可以动态的增加或减小)

Arrays can be created in two basic ways. The first is to use the Array constructor:

var colors = new Array();

If you know the number of items that will be in the array, you can pass the count into the constructor, and the length property will automatically be created with that value.

var colors = new Array(20);

The Array constructor can also be passed items that should be included in the array. The following creates an array with three string values:

var colors = new Array("red", "blue", "green");

The second way to create an array is by using array literal notation(数组描述符号):

var colors = ["red", "blue", "green"]; //creates an array with three strings
var names = [];                        //creates an empty array
var values = [1,2,];                   //AVOID! Creates an array with 2 or 3 items
var options = [,,,,,];                 //AVOID! creates an array with 5 or 6 items

The third line shows the effects of leaving a comma after the last value in an array literal: in Internet Explorer 8 and earlier, values becomes a three-itemarray containing the values 1, 2, and undefined; in all other browsers, values is a two-item array containing the values 1 and 2. This is due to a bug regarding array literals in the Internet Explorer implementation of ECMAScript through version 8 of the browser.为了不引发错误,后两种定义方式,最好不要使用)

The number of items in an array is stored in the length property, which always returns 0 or more.(数组中存放的数值个数,使用length属性来获取)

A unique characteristic of length is that it’s not read-only. By setting the  length property, you can easily remove items from or add items to the end of the array.(与其他语言不同,数组的length属性是可以修改的,通过修改length属性的值,可以添加或者删除数组中的元素)

var colors = ["red", "blue", "green"];    //creates an array with three strings
colors.length = 2;
alert(colors[2]);        //undefined

3.Detecting Arrays(检测数组类型)
Ever since ECMAScript 3 was defined, one of the classic problems has been truly determining whether a given object is an array. When dealing with a single web page, and therefore a single global scope, the " instanceof " operator works well

if (value instanceof Array){
    //do something on the array
}

The one problem with  instanceof is that it assumes a single global execution context. If you are dealing with multiple frames in a web page, you’re really dealing with two distinct global execution contexts and therefore two versions of the  Array constructor. If you were to pass an array from one frame into a second frame, that array has a different constructor function than an array created natively in the second frame. 

(只在一个全局作用域下,instanceof 操作符可以很好的检测对象是不是数组类型,但是在有frame的页面中,由于frame的存在,页面中会有多个全局作用域,当将一个作用域下的array复制给另一个作用域下的array时,有可能会存在由于Array的构造函数一样,造成复制错误)???

To work around this problem, ECMAScript 5 introduced the  Array.isArray() method. The purpose of this method is to definitively determine if a given value is an array regardless of the global execution context in which it was created.

if (Array.isArray(value)){
    //do something on the array
}

 4.Array的valueOf(),toString(),toLocalString()方法:

The toString() and valueOf() methods return the same value when called on an array. The result is a comma-separated string that contains the string equivalents of each value in the array, which is to say that each item has its toString() method called to create the final string.

When toLocaleString() is called on an array, it creates a comma-delimited string of the array values. The only difference between this and the two other methods is that toLocaleString() calls each item’s toLocaleString() instead of toString() to get its string value.

(toString()和valueOf()返回相同的值,他们的返回值是数组的每个元素调用toString()方法,然后加上","构成的字符串。toLocalString()的返回值是数组的每个元素调用toLocalString()方法,然后加上","构成的字符串)

var person1 = {
    toLocaleString : function () {
        return "Nikolaos";
    },
    
    toString : function() {
        return "Nicholas";
    }
};
                   
var person2 = {
    toLocaleString : function () {
        return "Grigorios";
    },
    
    toString : function() {
        return "Greg";
    }
};
                   
var people = [person1, person2];
alert(people);                      //Nicholas,Greg
alert(people.toString());           //Nicholas,Greg
alert(people.toLocaleString());     //Nikolaos,Grigorios

* If an item in the array is null or undefined, it is represented by an empty string in the result of join(), toLocaleString(), toString(), and valueOf().

5.Array的sort()方法:

By default, the sort() method puts the items in ascending order — with the smallest value first and the largest value last. To do this, the sort() method calls the String() casting function on every item and then compares the strings to determine the correct order. This occurs even if all items in an array are numbers

默认情况下,sort()方法会将所有的元素按升序的方式排序-值小的元素排在前面,值大的的元素排在后面。在排序过程中,sort()方法会调用的每个元素的toString()方法。即使在数字类型的时候,也是这样处理的。

var values = [0, 1, 5, 10, 15];
values.sort();
alert(values);    //0,1,10,15,5  按字符串值排序的

the sort() method allows you to pass in a comparison function that indicates which value should come before which.(在sort方法中使用一个 comparison 函数来比较元素的大小)

A comparison function accepts two arguments and returns a negative number if the first argument should come before the second, a zero if the arguments are equal, or a positive number if the first argument should come after the second.

//升序
function compare(value1, value2) { if (value1 < value2) { return -1; } else if (value1 > value2) { return 1; } else { return 0; } } var values = [0, 1, 5, 10, 15]; values.sort(compare); alert(values); //0,1,5,10,15
//降序
function compare(value1, value2) { if (value1 < value2) { return 1; } else if (value1 > value2) { return -1; } else { return 0; } } var values = [0, 1, 5, 10, 15]; values.sort(compare); alert(values); //15,10,5,1,0

6.Array中的其他方法:

The concat() method, for instance, allows you to create a new array based on all of the items in the current array. This method begins by creating a copy of the array and then appending the method arguments to the end and returning the newly constructed array. When no arguments are passed in, concat() simply clones the array and returns it. If one or more arrays are passed in, concat() appends each item in these arrays to the end of the result. If the values are not arrays, they are simply appended to the end of the resulting array.

var colors = ["red", "green", "blue"];
var colors2 = colors.concat("yellow", ["black", "brown"]);
                   
alert(colors);     //red,green,blue        
alert(colors2);    //red,green,blue,yellow,black,brown

The slice() method may accept one or two arguments: the starting and stopping positions of the items to return. If only one argument is present, the method returns all items between that position and the end of the array. If there are two arguments, the method returns all items between the start position and the end position, not including the item in the end position. Keep in mind that this operation does not affect the original array in any way.

var colors = ["red", "green", "blue", "yellow", "purple"];
var colors2 = colors.slice(1);
var colors3 = colors.slice(1,4);
                   
alert(colors2);   //green,blue,yellow,purple
alert(colors3);   //green,blue,yellow
alert(colors);     //red, green, blue, yellow, purple

*If either the start or end position of slice() is a negative number, then the number is subtracted from the length of the array to determine the appropriate locations. For example, calling slice(-2, -1) on an array with five items is the same as calling slice(3, 4). If the end position is smaller than the start, then an empty array is returned(负数是按倒数在数组中取元素)

splice() is to insert items into the middle of an array, but there are three distinct ways of using this method.

➤Deletion — Any number of items can be deleted from the array by specifying just two arguments: the position of the fi rst item to delete        and the number of items to delete. For example, splice(0, 2) deletes the first two items.
➤Insertion — Items can be inserted into a specifi c position by providing three or more arguments: the starting position, 0 (the number of  items to delete), and the item to insert. Optionally, you can specify a fourth parameter, fi fth parameter, or any number of other
 parameters to insert. For example, splice(2, 0, “red”, “green”) inserts the strings “red” and “green” into the array at position 2.
➤Replacement — Items can be inserted into a specifi c position while simultaneously deleting items, if you specify three arguments: the     starting position, the number of items to delete, and any number of items to insert. The number of items to insert doesn’t have to   match the number of items to delete. For example, splice(2, 1, “red”, “green”) deletes one item at position 2 and then inserts the strings  “red” and “green” into the array at position 2.

The splice() method always returns an array that contains any items that were removed from the array (or an empty array if no items were removed).

var colors = [“red”, “green”, “blue”];
var removed = colors.splice(0,1);                  //remove the first item
alert(colors);     //green,blue
alert(removed);    //red - one item array
                   
removed = colors.splice(1, 0, “yellow”, “orange”); //insert two items at position 1
alert(colors);     //green,yellow,orange,blue
alert(removed);    //empty array
                   
removed = colors.splice(1, 1, “red”, “purple”);    //insert two values, remove one
alert(colors);     //green,red,purple,orange,blue
alert(removed);    //yellow - one item array

Iterative Methods(用于遍历的方法):

ECMAScript 5 defines five iterative methods for arrays. Each of the methods accepts two arguments: a function to run on each item and an optional scope object in which to run the function (affecting the value of this). The function passed into one of these methods will receive three arguments: the array item value, the position of the item in the array, and the array object itself. Depending on the method, the results of this function’s execution may or may not affect the method’s return value. The iterative methods are as follows:

➤every() — Runs the given function on every item in the array and returns true if the function returns true for every item.
➤filter() — Runs the given function on every item in the array and returns an array of all items for which the function returns true.
➤forEach() — Runs the given function on every item in the array. This method has no return value.
➤map() — Runs the given function on every item in the array and returns the result of each function call in an array.
➤some() — Runs the given function on every item in the array and returns true if the function returns true for any one item.
These methods do not change the values contained in the array.

every()和some()方法:

var numbers = [1,2,3,4,5,4,3,2,1];
                   
var everyResult = numbers.every(function(item, index, array){
    return (item > 2);
});
                   
alert(everyResult);       //false
                   
var someResult = numbers.some(function(item, index, array){
    return (item > 2);
});
                   
alert(someResult);       //true

filter()方法:

var numbers = [1,2,3,4,5,4,3,2,1];

var filterResult = numbers.filter(function(item, index, array){
return (item > 2);
});

alert(filterResult); //[3,4,5,4,3]

map方法:

var numbers = [1,2,3,4,5,4,3,2,1];
                   
var mapResult = numbers.map(function(item, index, array){
    return item * 2;
});
                   
alert(mapResult);   //[2,4,6,8,10,8,6,4,2]

forEach()方法:

var numbers = [1,2,3,4,5,4,3,2,1];
                   
numbers.forEach(function(item, index, array){
    //do something here
});

reduce()和reduceRight()方法:

/**
 * javascript 中的reduce方法 和 reduceRight方法
 * 这两个方法是ECMAScript5中新增的方法
 * 都接受两个参数:第一个是用来迭代的数组的函数,这个函数有四个参数分别是,前一个值,当前值,项的索引,数组对象。然而这个函数的任何值都会作为第一个参数自动传给下一项。第二个是作为第一个函数中第一个参数的初始值
 *    
 * reduceRight 和 reduce一样,只是他是从右向左进行迭代的
 * 支持的浏览器有,IE9+,Firefox3+,Safari4+,Opera 10.5+,chrome 
 */
var nums = [1,2,3,4,5,6,7];

var sum = nums.reduce(function(prev, cur, index, array) {
    alert(prev + '------' + cur);  //8--1,9--2,11--3,14-4,18-5,23-6,29-7
    return prev + cur;
},8);
alert(sum); //36

 7.FUNCTION Type (函数)

function names are simply pointers to functions, they act like any other variable containing a pointer to an object. This means it’s possible to have multiple names for a single function.

function sum(num1, num2){
    return num1 + num2;
}        
alert(sum(10,10));    //20
                   
var anotherSum = sum;        
alert(anotherSum(10,10));  //20
                   
sum = null;        
alert(anotherSum(10,10));  //20

No Overloading (Revisited)没有重载

Thinking of function names as pointers also explains why there can be no function overloading in ECMAScript.

function addSomeNumber(num){
    return num + 100;
}
                   
function addSomeNumber(num) {
    return num + 200;
}
                   
var result = addSomeNumber(100);    //300

//上面的代码与下面的等价
var addSomeNumber = function (num){
    return num + 100;
};
                   
addSomeNumber = function (num) {
    return num + 200;
};
                   
var result = addSomeNumber(100);    //300

 

 





 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值