1 var colors = new Array(3); //创建一个包含3项的数组2 var names = new Array("Greg"); //创建一个包含1项,即字符串“Greg”的数组
1 var colors = ["red", "blue", "green"]; //创建一个包含3个字符串的数组2 alert(colors.toString()); //red,blue,green3 alert(colors.valueOf()); //red,blue,green4 alert(colors); //red,blue,green
1 var colors = ["red", "green", "blue"];2 alert(colors.join(",")); //red,green,blue3 alert(colors.join("||")); //red||green||blue
1 var colors = ["red", "blue"];2 colors.push("brown"); //添加另一项3 colors[3] = "black"; //添加一项4 alert(colors.length); //45 6 var item = colors.pop(); //取得最后一项7 alert(item); //"black"
1 var colors = new Array(); //创建一个数组2 var count = colors.push("red", "green"); //推入两项3 alert(count); //24 5 count = colors.push("black"); //推入另一项6 alert(count); //37 8 var item = colors.shift(); //取得第一项9 alert(colors.length); //2
1 var values = [1, 2, 3, 4, 5];2 values.reverse();3 alert(values); //5,4,3,2,1
1 function compare(value1, value2) { 2 if (value1 < value2) { 3 return 1; 4 } else if (value1 > value2) { 5 return -1; 6 } else { 7 return 0; 8 } 9 }10 11 var values = [0, 1, 5, 10, 15];12 values.sort(compare);13 alert(values); //15,10,5,1,0
1 var colors = ["red", "green", "blue"];2 var colors2 = colors.concat("yellow", ["black", "brown"]);3 4 alert(colors); //red,green,blue 5 alert(colors2); //red,green,blue,yellow,black,brown
1 var colors = ["red", "green", "blue", "yellow", "purple"];2 var colors2 = colors.slice(1);3 var colors3 = colors.slice(1,4);4 5 alert(colors2); //green,blue,yellow,purple6 alert(colors3); //green,blue,yellow
1 var colors = ["red", "green", "blue"]; 2 var removed = colors.splice(0,1); //删除第一项 3 alert(colors); //green,blue 4 alert(removed); //red,返回的数组中只包含一项 5 6 removed = colors.splice(1, 0, "yellow", "orange"); //从位置1开始插入两项 7 alert(colors); //green,yellow,orange,blue 8 alert(removed); //返回的是一个空数组 9 10 removed = colors.splice(1, 1, "red", "purple"); //插入两项,删除一项11 alert(colors); //green,red,purple,orange,blue12 alert(removed); //yellow,返回的数组中只包含 一项
1 var numbers = [1,2,3,4,5,4,3,2,1]; 2 3 alert(numbers.indexOf(4)); //3 4 alert(numbers.lastIndexOf(4)); //5 5 6 alert(numbers.indexOf(4, 4)); //5 7 alert(numbers.lastIndexOf(4, 4)); //3 8 var person = { name: "Nicholas" }; 9 var people = [{ name: "Nicholas" }];10 var morePeople = [person];11 12 alert(people.indexOf(person)); //-113 alert(morePeople.indexOf(person)); //0
1 var numbers = [1,2,3,4,5,4,3,2,1]; 2 3 var everyResult = numbers.every(function(item, index, array){ 4 return (item > 2); 5 }); 6 7 alert(everyResult); //false 8 9 var someResult = numbers.some(function(item, index, array){10 return (item > 2);11 });12 13 alert(someResult); //true
1 var numbers = [1,2,3,4,5,4,3,2,1];2 3 var filterResult = numbers.filter(function(item, index, array){4 return (item > 2);5 });6 7 alert(filterResult); //[3,4,5,4,3]
1 var numbers = [1,2,3,4,5,4,3,2,1];2 3 var maPResult = numbers.map(function(item, index, array){4 return item * 2;5 });6 7 alert(mapResult); //[2,4,6,8,10,8,6,4,2]
新闻热点
疑难解答