ES5 -- Array

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Array</title>
</head>
<body>
<script>
// 创建数组
let arr = new Array();
let arr2 = Array();
let arr3 = [];
console.log(arr, arr2, arr3); // Array(0), Array(0), Array(0)
// 增加
arr3[0] = 1;
arr3[arr3.length] = 2;
arr3.push(3);
console.log(arr3); // [1, 2, 3]
arr3.unshift(0);
console.log(arr3); // [0, 1, 2, 3]
// 删除
delete arr3[2];
console.log(arr3); // [0, 1, empty, 3]
console.log(arr3.length); // 4
console.log(2 in arr); // false
arr3.length -= 1;
console.log(arr3); // [0, 1, empty]
arr3.pop();
console.log(arr3); // [0, 1]
arr3.shift();
console.log(arr3); // [1]

// join()
const arr4 = [1,2,3];
console.log(arr4.join()); // '1,2,3'
console.log(arr4.join('-')); // '1-2-3'
function repeatString(str, n){
return new Array(n + 1).join(str);
}
const str = repeatString('aa', 3);
const str2 = repeatString('Hi', 5);
console.log(str); // 'aaaaaa'
console.log(str2); // 'HiHiHiHiHi'

// reverse()
const arr5 = [1,2,3,6,4,5];
arr5.reverse();
console.log(arr5); // [5,4,6,3,2,1]

// sort()
const arr6 = ['a','c','d','b'];
arr6.sort();
console.log(arr6); // ['a','b','c','d']

const arr7 = [21,12,23,42,32,6,7,8];
arr7.sort();
console.log(arr7); // [12, 21, 23, 32, 42, 6, 7, 8]

const arr8 = arr7.sort(function(a, b){
return a - b;
});
console.log(arr8); // [6, 7, 8, 12, 21, 23, 32, 42]

const arr9 = arr7.sort(function(a, b){
return b - a;
});
console.log(arr9); // [42, 32, 23, 21, 12, 8, 7, 6]

const arr10 = [{age: 23},{age: 263},{age: 233}];
const arr11 = arr10.sort(function(a, b){
return a.age - b.age;
});
console.log(arr11); // {age: 23} {age: 233} {age: 263}

// concat()
const arr12 = [1,2,3];
const arr13 = [[10,11],13];
console.log(arr12.concat(4,5)); // [1,2,3,4,5]
console.log(arr13.concat(14,15)); // [[10, 11], 13, 14, 15]

// slice()
const arr14 = [1,2,3,4,5];
console.log(arr14.slice(1)); // [2,3,4,5]
console.log(arr14.slice(2, 3)); // [3]
console.log(arr14.slice(-3, -1)); // [3, 4],倒数的下标是从1开始 不是0

// splice()
let arr15 = [2,3,4,5,6];
arr15.splice(2);
console.log(arr15); // [2,3]
arr15 = [2,3,4,5,6];
arr15.splice(2, 2);
console.log(arr15); // [2,3,6]
arr15 = [2,3,4,5,6];
arr15.splice(1,2,'a','b');
console.log(arr15); // [2, "a", "b", 5, 6]
</script>
</body>
</html>

评论 ( 0 )
最新评论
暂无评论

赶紧努力消灭 0 回复