// 创建一个数组
let fruits = ["apple", "banana", "orange"];
// 访问数组元素
console.log(fruits[0]); // 输出: apple
// 添加元素到数组末尾
fruits.push("grape");
console.log(fruits); // 输出: ["apple", "banana", "orange", "grape"]
// 删除数组最后一个元素
fruits.pop();
console.log(fruits); // 输出: ["apple", "banana", "orange"]
// 获取数组长度
console.log(fruits.length); // 输出: 3
// 遍历数组
fruits.forEach(function(fruit) {
console.log(fruit);
});
// 输出:
// apple
// banana
// orange
// 查找数组中是否存在某个元素
let index = fruits.indexOf("banana");
if (index !== -1) {
console.log("找到元素,索引为: " + index); // 输出: 找到元素,索引为: 1
} else {
console.log("未找到元素");
}
// 数组排序
let numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
return a - b;
});
console.log(numbers); // 输出: [1, 2, 3, 4, 5]
[] 来创建一个数组。push() 方法将新元素添加到数组末尾。pop() 方法删除数组的最后一个元素。length 属性获取数组的长度。forEach() 方法遍历数组中的每个元素。indexOf() 方法查找数组中某个元素的索引。sort() 方法对数组进行排序,默认按字母顺序或数字大小排序。下一篇:nodejs post请求
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站