其他分享
首页 > 其他分享> > 内置对象Array-2

内置对象Array-2

作者:互联网

pop()

let arr = [1, 2, 3, 4];
for(let i = 0, time = 1; i < arr.length; time++) {
  console.log(`------\n第 ${time} 次遍历:`);
  console.log(arr.pop());
  console.log(arr);
}

push()

let arr = [];
arr.push(1);
arr.push('2');
arr.push([3, 4, 5]);
arr.push([...6, 7, 8]);
console.log(arr);

/*
[1, "2", Array(3), 6, 7, 8]
0: 1
1: "2"
2: (3) [3, 4, 5]
3: 6
4: 7
5: 8
length: 6
*/

reverse()

let arr = [1, 2, 3];
arr.reverse();
console.log(arr); // [3, 2, 1]

shift()

let str = [1, 2, 3];
console.log(str.shift()); // 1
console.log(str.shift()); // 2
console.log(str.shift()); // 3
console.log(str.shift()); // undefined

unshift()

let arrA = ['1'];
arrA.unshift('0');
console.log(arrA); // ['0', '1']

let arrB = [4, 5, 6];
arrB.unshift(1, 2, 3);
console.log(arrB); // [1, 2, 3, 4, 5, 6]

slice()

var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'];
var citrus = fruits.slice(1, 3);

// fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
// citrus contains ['Orange','Lemon']

splice()

var months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');

console.log(months);
// ['Jan', 'Feb', 'March', 'April', 'June']

months.splice(4, 1, 'May');

console.log(months);
// ['Jan', 'Feb', 'March', 'April', 'May']

sort()

[4, 2, 5, 1, 3].sort(), // [1, 2, 3, 4, 5]
[4, 2, 5, 1, 3].sort((a, b) => a < b), // [5, 4, 3, 2, 1]
['a', 'd', 'c', 'b'].sort(), // ['a', 'b', 'c', 'd']
['jsliang', 'eat', 'apple'].sort(), // ['apple', 'eat', 'jsliang']

toString()

let num = 123;
num.toString(); // '123'

标签:arr,内置,console,log,对象,元素,数组,MDN,Array
来源: https://blog.csdn.net/weixin_43956521/article/details/111470733