阅读目录
声明数组
数组是多个变量值的集合,数组是Array 对象的实例,所以可以像对象一样调用方法。
创建数组
使用对象方式创建数组
console.log(new Array(1, 'wgchen', 'willem')); // [1, 'wgchen', 'willem']
使用字面量创建是推荐的简单作法
const array = ["wgchen", "willem"];
多维数组定义
const array = [["wgchen"], ["willem"]];
console.log(array[1][0]); // willem
数组是引用类型可以使用 const
声明并修改它的值
const array = ["wgchen", "willem"];
array.push("ycc");
console.log(array); // ['wgchen', 'willem', 'ycc']
使用原型的 length 属性可以获取数组元素数量
let hd = ["wgchen", "willem"];
console.log(hd.length); //2
数组可以设置任何值,下面是使用索引添加数组
let hd = ["wgchen"];
hd[1] = "willem";
console.log(hd) // ['wgchen', 'willem']
下面直接设置 3
号数组,会将 1/2
索引的数组定义为空值
let hd = ["wgchen"];
hd[3] = "willem";
console.log(hd.length); //4
console.log(hd); // ['wgchen', 空 ×2, 'willem']
声明多个空元素的数组
let hd = new Array(3);
console.log(hd.length);
console.log(hd);
Array.of
使用 Array.of 与 new Array 不同是设置一个参数时不会创建空元素数组
let hd = Array.of(3);
console.log(hd); //[3]
hd = Array.of(1, 2, 3);
console.log(hd); //[1, 2, 3]
类型检测
检测变量是否为数组类型
console.log(Array.isArray([1, "wgchen", "willem"])); //true
console.log(Array.isArray(9)); //false
类型转换
可以将数组转换为字符串也可以将其他类型转换为数组。
字符串转数组
大部分数据类型都可以使用.toString() 函数转换为字符串。
console.log(([1, 2, 3]).toString()); // 1,2,3
也可以使用函数 String 转换为字符串。
console.log(String([1, 2, 3]));
或使用 join 连接为字符串
console.log([1, 2, 3].join("-"));//1-2-3
Array.from 将类数组转换为数组
使用 Array.from 可将类数组转换为数组,类数组指包含 length 属性或可迭代的对象。
第一个参数为要转换的数据
第二个参数为类似于map 函数的回调方法
let str = 'wgcehn';
console.log(Array.from(str)); // ['w', 'g', 'c', 'e', 'h', 'n']
为对象设置 length 属性后也可以转换为数组,但要下标为数值或数值字符串
let user = {
0: 'wgchen',
'1': 18,
length: 2
};
console.log(Array.from(user)); // ["wgchen", 18]
DOM元素转换为数组后来使用数组函数,
第二个参数类似于map 函数的方法,可对数组元素执行函数处理。
<body>
<button message="wgchen">button</button>
<button message="willem">button</button>
</body>
<script>
let btns = document.querySelectorAll('button');
console.log(btns); //包含length属性
Array.from(btns, (item) => {
item.style.background = 'red';
});
</script>
展开语法
使用展开语法将 NodeList 转换为数组操作
<style>
.hide {
display: none;
}
</style>
<body>
<div>wgchen</div>
<div>willem</div