面試官最愛問的JAVAScript數(shù)組方法和屬性都在這里,下面是 JavaScript 常用的數(shù)組方法和屬性介紹,以及簡單的代碼示例:
JavaScript數(shù)組方法和屬性
一、數(shù)組屬性:
1、length:返回數(shù)組的元素個數(shù)。
const arr = [1, 2, 3];
console.log(arr.length); // 3
2、prototype:允許您向?qū)ο筇砑訉傩院头椒ā?/p>
Array.prototype.newMethod = function() {
// 添加新方法
};
3、constructor:返回創(chuàng)建任何對象時使用的原型函數(shù)。
const arr = [];
console.log(arr.constructor); // [Function: Array]
二、數(shù)組方法:
1、push():將一個或多個元素添加到數(shù)組的末尾,并返回新數(shù)組的長度。
const arr = [1, 2, 3];
arr.push(4);
console.log(arr); // [1, 2, 3, 4]
2、pop():從數(shù)組的末尾刪除一個元素,并返回該元素的值。
const arr = [1, 2, 3];
const lastElement = arr.pop();
console.log(lastElement); // 3
console.log(arr); // [1, 2]
3、shift():從數(shù)組的開頭刪除一個元素,并返回該元素的值。
const arr = [1, 2, 3];
const firstElement = arr.shift();
console.log(firstElement); // 1
console.log(arr); // [2, 3]
4、unshift():在數(shù)組的開頭添加一個或多個元素,并返回新數(shù)組的長度。
const arr = [1, 2, 3];
arr.unshift(4, 5);
console.log(arr); // [4, 5, 1, 2, 3]
5、splice():向/從數(shù)組中添加/刪除元素,然后返回被刪除元素的新數(shù)組。
const arr = [1, 2, 3];
arr.splice(1, 1, 'a', 'b');
console.log(arr); // [1, 'a', 'b', 3]
6、concat():用于連接兩個或多個數(shù)組。
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const newArr = arr1.concat(arr2);
console.log(newArr); // [1, 2, 3, 4, 5, 6]
7、slice():從指定數(shù)組中提取子數(shù)組。
const arr = [1, 2, 3, 4, 5];
const subArr = arr.slice(1, 4);
console.log(subArr); // [2, 3, 4]
8、indexOf():查找指定元素在數(shù)組中的位置。
const arr = [1, 2, 3, 4, 5];
const index = arr.indexOf(3);
console.log(index); // 2
9、join():把數(shù)組中的所有元素放入一個字符串。
const arr = ['red', 'green', 'blue'];
const str = arr.join('-');
console.log(str); // "red-green-blue"
以上就是 JavaScript 常用的數(shù)組方法和屬性,應(yīng)該能滿足大部分的需求。






