
1。为数组中第二大元素编写代码。
代码:
立即学习“Java免费学习笔记(深入)”;
const arr=[2,3,4,6,78,0,1,0,2,3,455,8,9];
function secondlargest(arr){
const sortedarray=[...new set(arr)].sort((a,b)=>b-a);
return sortedarray.length>=2 ? sortedarray[1] : null;
}
console.log("second largest element:",secondlargest(arr));
输出:
second largest element: 78
*2。编写代码对数组进行排序,而不使用内置
功能。 *
代码:
立即学习“Java免费学习笔记(深入)”;
const arr=[2,3,4,6,78,0,1,0,2,3,455,8,9];
function sortarray(arr){
let temp=0;
for(let i=0;i<arr.length;i++){
for(let j=arr.length-1;j>i;j--){
if(arr[i]>arr[j]){
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
return arr;
}
console.log("sorted array:",sortarray(arr));
输出:
sorted array: [
0, 0, 1, 2, 2, 3,
3, 4, 6, 8, 9, 78,
455
]
3。不使用“set”找出数组中唯一的元素。
代码:
立即学习“Java免费学习笔记(深入)”;
const arr=[2,3,4,6,78,0,1,0,2,3,455,8,9];
function uniquearray(arr){
let temparray=[];
for(let i=0;i<arr.length;i++){
if(temparray.indexof(arr[i])===-1){
temparray.push(arr[i]);
}
}
return temparray;
}
console.log("unique array of element:",uniquearray(arr));
输出:
unique array of element: [
2, 3, 4, 6, 78,
0, 1, 455, 8, 9
]
4。编写不使用内置
反转数组的代码
函数。
代码:
立即学习“Java免费学习笔记(深入)”;
const arr=[2,3,4,6,78,0,1,0,2,3,455,8,9];
function reversearray(arr){
let temparray=[];
for(let i=arr.length-1;i>0;i--){
temparray.push(arr[i]);
}
return temparray;
}
console.log("reverse array of elements:",reversearray(arr));
输出:
Reverse Array of Elements: [
9, 8, 455, 3, 2,
0, 1, 0, 78, 6,
4, 3
]
希望这对您有用。祝你有美好的一天!
以上就是Javascript 面试编码问题的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号