Article directory
iterate over the array
PS: This article only explains the last three
- while
- for( ; ; )
- for in
- for of
- map
let arr = ["a","b","c","d","e","f"];
for( var i in arr)//i是索引
for( var i of arr)//i是数组种具体的值
/*map的参数是一个回调函数,function的值作为map的参数*/
arr.map(function(value,index){
/*value是arr的值,index是数组的索引,记住参数顺序不能改变*/
})
Common methods for manipulating arrays
- push
- map
- sort
- filter
- join
1:push
let newArr= [];
newArr.push("arr[i]");
--------------------------------------------
2:map/*map和filter的参数都是回调函数*/
/*从一个数组中筛选数据用arr.filter()*/
arr.map(function(value,index){
})
--------------------------------------------
3:sort
let arr = [1,3,2,6,5,4];
arr.sort();//自动排序
--------------------------------------------
4:filter/*map和filter的参数都是回调函数*/
let newArray = arr.filter(function(item) {
if (item > 3) {
return item;
}
})
--------------------------------------------
5:join
//join 数组 拆分成 字符串
let arr = [1,3,2,6,5,4];
let str = arr.join(""); //1,3,2,6,5,4
let str1 = arr.join(); //132654
let str2 = arr.join("*"); //1*3*2*6*5*4
--------------------------------------------
6:string的split/*1-5方法都是 数组的方法 而本方法是字符的方法*/
//split 字符串 分裂成 数组
let str = "apple"
let str1 = str.split(); //['apple']
let str2 = str.split(""); //['a', 'p', 'p', 'l', 'e']
let str3 = str.split("+"); //['apple'] 因为apple字符串里面没有+符号
let str4 = str.split("l"); //['app', 'e']
let str5 = str.split("p"); //['a', '', 'le'] 因为有2个p,所以第2个p就变为''
example
Example 1: Find the index of the maximum value in an array
let arr = [1, 3, 2, 4, 5, 6, 8, 9];
let max = 0;
let realindex = 0;
arr.map(function(item, index) {
//此处写filter和map函数都是一样的结果
if (item > max) {
max = item;
realindex = index;
}
})
console.log(realindex);
console.log(max);
Example 2: Filter out all the information of the boys below and add them to a new array
let list = [
{name: "Xiao Ming",age: 8,sex: "Male"}, {
name: "Xiao Gang",age: 9, sex: "Male"},
{name: "Xiaohong",age:9,sex: "Female"}
]
method one
let newArr = list.filter(function(value, index) {
//此处用filter和map得到的结果:分别有2个元素,3个元素(第3个为undefined)
if (value.sex === "男") {
return value;
}
})
Method Two
let newArr = [];
for (let i = 0; i < list.length; i++) {
if (list[i].sex === "男") {
newArr.push(list[i]);
}
}
method three
let newArr = [];
for (let i of list) {
if (i.sex === "男") {
newArr.push(i);
}
}