js的一些常用命令
一、数组相关
1.查询数组内单个坐标
array.indexof
会返回指定元素坐标
let a = [1, 2, "aa"]; let index_aa = a.indexof("aa") console.log(index_aa)
2.删除数组指定坐标
array.splice(数组下标,1)
会修改原数组的长度
delete arr[数组下标]
会将数组的下标位置变成undefined,长度不变
其他一些常用方法:
array.push 从末尾添加数组元素,长度加1
array.pop 从末尾删除,长度减1
array.shift 从数组最前面删除,长度减1
array.unshift 从数组最前面添加,长度加1
二、循环相关
1.for循环
最基本也是最早的for循环,利用数字循环遍历
for (var i = 1; i <= 10; i++) {
console.log(i + " ");
}
for in 遍历对象, 其中的会将对象的key拿出来,然后使用进去。数组也可以这样遍历,但是好像官方不太推荐,但是实际开发中,我for in 是用得比较多的,因为常常需要用到key,而for of 没有key,只有数组的值
// 定义一个对象 var person = {"name": "Clark", "surname": "Kent", "age": "36"}; // 遍历对象中的所有属性 for(var key in person) {
console.log(person[key]);
}
for of 遍历数组,
// 定义一个数组 var arr = ['a', 'b', 'c', 'd', 'e', 'f']; // 使用 for of 循环遍历数组中的每个元素 for (var value of arr) { console.log(value + ", "); } // 定义一个字符串 var str = "Hello World!"; // 使用 for of 循环遍历字符串中的每个字符 for (var value of str) { console.log(value + ", "); }