1、将数组中的每一个数转分别换为字符串
const strs = arr.map(String);
2、sort()方法默认排序规则:
[3, 15, 8].sort(); // 结果:[15, 3, 8](按字符串比较:"15" < "3" < "8")
sort函数的定义:
arr.sort((a, b) => {
// 返回值决定a和b的顺序
// 若返回值 < 0,则a排在b前面
// 若返回值 = 0,则a和b的顺序不变
// 若返回值 > 0,则a排在b后面
});
升序排序
[3, 15, 8].sort((a, b) => a - b); // 结果:[3, 8, 15]
降序排序
[3, 15, 8].sort((a, b) => b - a); // 结果:[15, 8, 3]
sort()
方法允许传入一个 ** 比较函数(Comparator)** 来自定义排序规则 ,例如:
strs.sort((a, b) => {
return (a + b) - (b + a);
});
其中a
和 b
是数组中的字符串元素(如 "30"
和 "3"
),a + b
表示拼接后的字符串(如 "303"
),
b + a
表示反向拼接的字符串(如 "330"
)。若 (a + b) - (b + a) < 0
,说明 a + b
更小,则a
排在 b
前面。
3、map() 映射表
实现元素与索引的映射:
// score = [10, 3, 8] → map = {10: 0, 3: 1, 8: 2}
const map = new Map();
score.forEach((s, i) => map.set(s, i));
4、数组for循环可以用forEach进行替代
遍历方式 | 是否能访问索引 | 能否中断循环(break/continue) | 用途推荐 |
---|---|---|---|
forEach |
✅ 支持索引 | ❌ 不能中断循环 | 简单逐项处理 |
for |
✅ 支持索引 | ✅ 支持 | 需要灵活控制循环流程时使用 |
for...of |
❌ 不支持索引(除非自己定义变量) | ✅ 支持 | 只需值,不关心索引时使用 |
5、slice()
是 JavaScript 中数组的方法,用于 截取数组的一部分,并返回一个新数组,不会修改原数组。
arr.slice(start, end)
start:开始索引(包含该位置)
end:结束索引(不包含该位置)
如果不写 end,表示从 start 一直到数组末尾。
6、随机获取数组中的一个元素
const pivotIndex = Math.floor(Math.random() * nums.length);
const p = nums[pivotIndex];
7、注意 用forEach来遍历数组时无法在其中进行return作为整个函数的返回值
var majorityElement = function(nums) {
const arr = [...nums].sort((a,b)=>a-b);
const n = nums.length;
nums.forEach((s,i)=>{
if(arr.lastIndexOf(s)-arr.indexOf(s)+1>n/2) return s; //这个写法不对
})
};
forEach()
的 return
只是跳出当前回调函数,不会终止外层的 majorityElement
函数;
8、for...in 和for...of的区别
for...in
遍历得到的是字符串形式的索引,而非数值。若需要数值类型的索引,需手动转换:
const nums = [10, 20, 30];
for (const strIndex in nums) {
const numIndex = parseInt(strIndex, 10); // 转换为数值
console.log(numIndex); // 0, 1, 2(数值类型)
}
for...of
遍历数组的值,直接获取数组元素(数值类型):
for (const value of nums) {
console.log(value); // 10, 20, 30(数值类型)
}