Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

数组函数 #43

Open
qingfengmy opened this issue Aug 7, 2018 · 8 comments
Open

数组函数 #43

qingfengmy opened this issue Aug 7, 2018 · 8 comments

Comments

@qingfengmy
Copy link
Owner

1. splice

splice的意思是 粘接。
它是数组的函数。
它的作用是操作数组(增删改)
参数是(index,howmany,item1,item2,...);返回值是被删除的项目。

index: 必须,整数,操作的位置
howmany: 必须,整数,要删除的项目数量,如果为0则不会删除
item1...: 非必须,向数组添加的项目。

注意: splice会操作当前array.

var arr = ['a','b','c']
// 增
var result = arr.splice(1,0,'d'); // arr: a,d,b,c; result: []
// 删
var result = arr.splice(1,1);// arr: a,b,c; result: ['d']
// 改
var result = arr.splice(1,1,'e');// arr: a,e,c; result: ['b']
@qingfengmy
Copy link
Owner Author

2. slice

slice的意思是切片。
它是数组的函数。
它的作用是操作数组(查)
参数是(start, end);返回值是一个新数组。

var arr = ['a','b','c'];
var result = slice(1,2);// result:['b']

@qingfengmy
Copy link
Owner Author

3. shift/unshift/push/pop

shift:从集合中把第一个元素删除,并返回这个元素的值。

const arr = [1, 2, 3];
const result = arr.shift();
console.log(arr, result);//[2,3],1

unshift: 在集合开头添加一个或更多元素,并返回新的长度

const arr = [1, 2, 3];
const result = arr.unshift(4,5);
console.log(arr, result);//[ 4, 5, 1, 2, 3 ] 5

push:在集合中添加元素,并返回新的长度

const arr = [1, 2, 3];
const result = arr.push(4);
console.log(arr, result);//[ 1, 2, 3, 4 ] 4

pop:从集合中把最后一个元素删除,并返回这个元素的值。

const arr = [1, 2, 3];
const result = arr.pop();
console.log(arr, result);//[ 1, 2 ] 3

@qingfengmy
Copy link
Owner Author

reduce

[{price:2,num:3},{price:4,num:5}].reduce((total,current)=>total+current.price*current.num),0)
// 26

@qingfengmy
Copy link
Owner Author

indexof

只适合基本数据类型

[1,2,3,4,5].indexOf(4)
// 3
[1,true,false,4,5].indexOf(true)
// 1
[1,2,{price:3},{price:4}].indexOf({price:3})
// -1

@qingfengmy
Copy link
Owner Author

findIndex

[1,2,{price:3},{price:4}].findIndex(item=>item.price==4)
// 3

@qingfengmy
Copy link
Owner Author

find

[1,2,{price:3},{price:4}].find(item=>item.price==4)
// {price:4}

@qingfengmy
Copy link
Owner Author

some和every

some:有一个符合则遍历结束

every:有一个不符合则遍历结束

[1,2,3,4,-1].some(i=>i>0)
// true
[1,2,3,4,-1].every(i=>i>0)
// false

@qingfengmy
Copy link
Owner Author

sort

// 升序
var arr = [4,3,6,5,7,2,1];
arr.sort();
arr.sort(function(a,b){
    return a-b;
});
console.log(arr);
//输出结果[1234567]
// 降序
var arr = [4,3,6,5,7,2,1];
arr.sort();
arr.sort(function(a,b){
    return b-a;
});
console.log(arr);
//输出结果[7,6,5,4,3,2,1]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant