每天一篇javascript学习小结(Array数组)(2)

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

10、数组push和pop方法

var colors = new Array(); //create an array var count = colors.push("red", "green"); //push two items alert(count); //2 count = colors.push("black"); //push another item on alert(count); //3 var item = colors.pop(); //get the last item alert(item); //"black" alert(colors.length); //2

11、数组方法unshift和shift

//unshift() 方法可向数组的开头添加一个或更多元素,并返回新的长度。 //shift() 方法用于把数组的第一个元素从其中删除,并返回第一个元素的值。 var colors = new Array(); //create an array var count = colors.unshift("red", "green"); //push two items alert(count); //2 count = colors.unshift("black"); //push another item on alert(count); //3 var item = colors.pop(); //get the first item alert(item); //"green" alert(colors.length); //2

12、数组倒序方法reverse

var values = [1, 2, 3, 4, 5]; values.reverse(); alert(values); //5,4,3,2,1

13、数组排序方法sort

function compare(value1, value2) { if (value1 < value2) { return -1; } else if (value1 > value2) { return 1; } else { return 0; } } var values = [0, 1, 16, 10, 15]; values.sort(compare); alert(values); //0,1,10,15,16 //sort 改变原数组

14、数组方法slice

/* slice() 方法可从已有的数组中返回选定的元素。 语法 arrayObject.slice(start,end) start 必需。规定从何处开始选取。如果是负数,那么它规定从数组尾部开始算起的位置。也就是说,-1 指最后一个元素,-2 指倒数第二个元素,以此类推。 end 可选。规定从何处结束选取。该参数是数组片断结束处的数组下标。如果没有指定该参数,那么切分的数组包含从 start 到数组结束的所有元素。如果这个参数是负数,那么它规定的是从数组尾部开始算起的元素。 返回值 返回一个新的数组,包含从 start 到 end (不包括该元素)的 arrayObject 中的元素。 */ 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

15、数组方法splice

/* plice() 方法向/从数组中添加/删除项目,然后返回被删除的项目。 注释:该方法会改变原始数组。 语法 arrayObject.splice(index,howmany,item1,.....,itemX) index 必需。整数,规定添加/删除项目的位置,使用负数可从数组结尾处规定位置。 howmany 必需。要删除的项目数量。如果设置为 0,则不会删除项目。 item1, ..., itemX 可选。向数组添加的新项目。 */ 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

16、数组isArray()方法

alert(Array.isArray([])); //true alert(Array.isArray({})); //false

以上就是今天的javascript学习小结,之后每天还会继续更新,希望大家继续关注。

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wgzfpx.html