JavaScript数组面试题
-
创建一个包含多个元素的数组,并打印输出数组的内容。
javascriptconst array = ["apple", "banana", "orange"]; console.log(array);
-
如何访问数组中的特定元素?
javascriptconst array = ["apple", "banana", "orange"]; console.log(array[1]); // 输出:banana
-
如何向数组末尾添加新的元素?
javascriptconst array = ["apple", "banana", "orange"]; array.push("grape"); console.log(array);
-
如何检查数组中是否存在指定的元素?
javascriptconst array = ["apple", "banana", "orange"]; const exists = array.includes("banana"); if (exists) { console.log("存在"); } else { console.log("不存在"); }
-
如何在数组中搜索指定元素,并返回对应的索引?
javascriptconst array = ["apple", "banana", "orange"]; const index = array.indexOf("banana"); console.log(index); // 输出:1
-
如何遍历数组并输出每个元素?
javascriptconst array = ["apple", "banana", "orange"]; array.forEach(element => { console.log(element); });
-
如何获取数组的长度(即元素的个数)?
javascriptconst array = ["apple", "banana", "orange"]; const length = array.length; console.log(length); // 输出:3
-
如何按照字母顺序对数组进行排序?
javascriptconst array = ["apple", "banana", "orange"]; array.sort(); console.log(array);
-
如何计算数组中所有元素的总和?
javascriptconst array = [1, 2, 3, 4, 5]; const sum = array.reduce((accumulator, currentValue) => accumulator + currentValue, 0); console.log(sum); // 输出:15
-
如何查找数组中的最大值和最小值?
javascriptconst array = [5, 2, 9, 1, 7]; const min = Math.min(...array); const max = Math.max(...array); console.log("最小值:" + min); // 输出:1 console.log("最大值:" + max); // 输出:9