var arr = [1, 2, "c"];
var rel = arr.push("A", "B");
console.log(arr); // [1, 2, "c", "A", "B"]
console.log(rel); // 5 (数组长度)
var arr = [1, 2, "c"];
var rel = arr.unshift("A", "B");
console.log(arr); // [ "A", "B",1, 2, "c"]
console.log(rel); // 5 (数组长度)
var arr = [1, 2, "c"];
var rel = arr.pop();
console.log(arr); // [1, 2]
console.log(rel); // c
var arr = ["a","b", "c"];
var rel = arr.shift();
console.log(arr); // ['b', "c"]
console.log(rel); // a
var arr = [1, 2, 3, "a", "b", "c"];
var rel = arr.reverse();
console.log(arr); // ["c", "b", "a", 3, 2, 1]
console.log(rel); // ["c", "b", "a", 3, 2, 1]
var arr1 = [10, 1, 5, 2, 3];
//默认排序
arr1.sort();
//从小到大 a - b > 0 a 会被排列到 b 之前
arr1.sort((a,b)=>{return a - b})
//从大到小
arr1.sort((a,b)=>{return b - a})
//对象数组排序
var arr1 = [
{ name: "老八", age: "38" },
{ name: "赵日天", age: "28" },
{ name: "龙傲天", age: "48" },
];
arr1.sort(function (a, b) {
console.log(a, b);
return b.age - a.age;
});
console.log(arr1);
用法:array.splice(start,deleteCount,item…)
//替换元素
var a=['a','b','c'];
var b=a.splice(1,1,'e','f'); //a=['a','e','f','c'],b=['b']
//删除元素
var arr1 = [1,3,5,7,9,11];
var arrRemoved = arr1.splice(0,2);
console.log(arr1); // [5,7,9,11]
console.log(arrRemoved); // [1,3]
//添加元素
var arr1 = [22,3,31,12];
arr1.splice(1,0,12,35);
console.log(arr1); // [22,12,35,3,31,12]
var arr1 = [1,3,5,7];
var arrCopy = arr1.concat(9,[11,13]);
console.log(arrCopy); // [1,3,5,7,9,11,13]
console.log(arr1); // [1,3,5,7](原数组未被修改)
array.slice(start,end)
var arr1 = [1,2,3,4,5];
var arr2 = arr1.some(x => {
return x < 3;
});
console.log(arr2); // true
var arr3 = arr1.some(x => {
return x < 1;
});
console.log(arr3); // false
var arr1 = [1,2,3,4,5];
var sum = arr1.reduce((prev,cur,index,array) => {
return prev + cur;
},10); // 数组一开始加了一个初始值10,可以不设默认0
console.log(sum); // 25
var arr1 = [22,3,31,12];
let str = arr1.toLocaleString();
var str2 = arr1.toString();
console.log(str); // 22,3,31,12
console.log(str2); // 22,3,31,12
keys()是对键名的遍历、values()是对键值的遍历、entries()是对键值对的遍历
for(let index of [a,b].keys()){
console.log(index);
}
// 0
// 1
for(let elem of [a,b].values()){
console.log(elem);
}
// a
// b
for(let [index,elem] of [a,b].entries()){
console.log(index,elem);
}
// 0 'a'
// 1 'b'
返回某个指定的字符串值(基本数据类型)在字符串、数组中首次出现的位置