javascript 数组

本文深入讲解JavaScript中数组的各种方法,包括检测、转换、栈、队列、重排序、操作、位置及迭代方法,如push、pop、slice、splice、indexOf等,并提供了详细的使用示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里插入图片描述

  1. 检测数组
    if(Array.isArray(value)){//对数组进行某些操作}
  2. 转换方法
    var colors=["red","blue","yellow"]
    alert(colors.toString()); //red,blue,yellow
    alert(colors.valueOf()); //red,blue,yellow
    alert(colors.toLocaleString()); //red,blue,yellow 注意:toLocaleString()是将元素进行toLocaleString()转换后拼接的
    alert(colors); //red,blue,yellow
    alert(colors.join("||")); //red||blue||yellow
  3. 栈方法(后进先出)
    push() ,后进,参数可多个,从后面添加数组元素,返回数组长度。另外可直接通过指定数组位置添加元素 colors[5]="purple"
    pop(),先出,移除最后一个元素,返回移除元素。
  4. 队列方法(后进后出)
    push(),后进
    shift(),先出,移除数组的第一个元素,返回移除元素。
    unshift(),参数可多个,从前面添加数组元素,返回数组长度。
  5. 重排序方法
    reverse(),反转数组元素的顺序
    sort(),将数组元素转换为字符串后进行升序排列
var values = [0,1,5,10,15];
function compare(value1,value2)
{
		if(value1<value2)
		{
			return -1;
		}
		else if(value1>value2)
		{
		   return 1;
		}
		else
		{
			return 0;
		}
}
values.sort(compare);//升序排列
  1. 操作方法
    slice(),复制数组中某几项,形成一个新数组
    splice(startIndex,deleteItemCount,item1,item2,item3),其中startIndex,deleteItemCount为必填参数,可用于向数组删除、插入、替换元素,返回 删除的元素 组成的数组
/*slice*/
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

/*splice*/
var colors = ["red", "green", "blue"]; 
var removed = colors.splice(0,1); // 删除第一项
alert(colors); // green,blue 
alert(removed); // red,返回的数组中只包含一项
removed = colors.splice(1, 0, "yellow", "orange"); // 从位置 1 开始插入alert(colors); // green,yellow,orange,blue 
alert(removed); // 返回的是一个空数组
removed = colors.splice(1, 1, "red", "purple"); // 插入两项,删除一项
alert(colors); // green,red,purple,orange,blue 
alert(removed); // yellow,返回的数组中只包含一项
  1. 位置方法
    indexOf(item),返回元素在数组中的第一个索引。
    lastIndexOf(item),返回元素在数组中的最后一个索引。

  2. 迭代方法
    every():对数组中的每一项运行给定函数,如果该函数对每一项都返回 true,则返回 true
    filter():对数组中的每一项运行给定函数,返回该函数会返回 true 的项组成的数组。
    forEach():对数组中的每一项运行给定函数。这个方法没有返回值,修改的是数组本身。
    map():对数组中的每一项运行给定函数,返回每次函数调用的结果组成的数组
    some():对数组中的每一项运行给定函数,如果该函数对任一项返回 true,则返回 true

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值