1、打印出 1 - 10000 之间的所有对称数 例如:121、1331 等
[...Array(10000).keys()].filter((x) => {
return x.toString().length >= 1 && x === Number(x.toString().split('').reverse().join(''))
})
2、旋转数组
给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。
示例 1: 输入: [1, 2, 3, 4, 5, 6, 7] 和 k = 3 输出: [5, 6, 7, 1, 2, 3, 4] 解释: 向右旋转 1 步: [7, 1, 2, 3, 4, 5, 6] 向右旋转 2 步: [6, 7, 1, 2, 3, 4, 5] 向右旋转 3 步: [5, 6, 7, 1, 2, 3, 4]
示例 2: 输入: [-1, -100, 3, 99] 和 k = 2 输出: [3, 99, -1, -100] 解释: 向右旋转 1 步: [99, -1, -100, 3] 向右旋转 2 步: [3, 99, -1, -100]
function rotate(arr, k) {
const len = arr.length
const step = k % len
return arr.slice(-step).concat(arr.slice(0, len - step))}
// rotate([1, 2, 3, 4, 5, 6], 7) => [6, 1, 2, 3, 4, 5]
3、实现一个字符串匹配算法,从长度为 n 的字符串 S 中,查找是否存在字符串 T,T 的长度是 m,若存在返回所在位 置。
const find = (S, T) => {
if (S.length < T.length) return -1
for (let i = 0; i < S.length; i++) {
if (S.slice(i, i + T.length) === T) return i
console.log(5555,i)
}
return -1
}
4、如何把一个字符串的大小写取反(大写变小写小写 变大写),例如 ’AbC’ 变成 ‘aBc’
function processString (s) {
var arr = s.split('');
var new_arr = arr.map((item) => {
return item === item.toUpperCase() ? item.toLowerCase() :
item.toUpperCase();
});
return new_arr.join('');}
// console.log(processString('AbC')); aBc
5、数组编程题
随机生成一个长度为 10 的整数类型的数组,例如 [2, 10, 3, 4, 5, 11, 10, 11, 20],将其排列成一个新数组,要求新数组形式如下,例如 [[2, 3, 4, 5], [10, 11], [20]]。
function formArray(arr: any[]) {
const sortedArr = Array.from(new Set(arr)).sort((a, b) => a - b);
const map = new Map();
sortedArr.forEach((v) => {
const key = Math.floor(v / 10);
const group = map.get(key) || [];
group.push(v); map.set(key, group); });
return [...map.values()];
}
6、给定两个数组,写一个方法来计算它们的交集
例如:给定 nums1 = [1, 2, 2, 1],nums2 = [2, 2],返回 [2, 2]。 var nums1 = [1, 2, 2, 1], nums2 = [2, 2, 3, 4];
var newArr2 = nums1.filter((item) => {
return nums2.includes(item);
});
console.log(newArr2);
7、要求设计 LazyMan 类,实现以下功能
LazyMan('Tony');
// Hi I am Tony
LazyMan('Tony').sleep(10).eat('lunch');
// Hi I am Tony
// 等待了 10 秒...
// I am eating
lunchLazyMan('Tony').eat('lunch').sleep(10).eat('dinner');
// Hi I am Tony
// I am eating lunch
// 等待了 10 秒...
// I am eating
dinerLazyMan('Tony').eat('lunch').eat('dinner').sleepFirst(5).sleep(1 0).eat('junk food');
// Hi I am Tony
// 等待了 5 秒...
// I am eating lunch
// I am eating dinner
// 等待了 10 秒...
// I am eating junk food
class LazyManClass {
constructor(name) {
this.name = name
this.queue = []
console.log(`Hi I am ${name}`)
setTimeout(() => {
this.next()
},0)
}
sleepFirst(time) {
const fn = () => {
setTimeout(() => {
console.log(`等待了${time}秒...`)
this.next()
}, time) }
this.queue.unshift(fn)
return this
}
sleep(time) {
const fn = () => {
setTimeout(() => {
console.log(`等待了${time}秒...`)
this.next()
},time)
}
this.queue.push(fn)
return this
}
eat(food) {
const fn = () => {
console.log(`I am eating ${food}`)
this.next() }
this.queue.push(fn)
return this
}
next() {
const fn = this.queue.shift()
fn && fn()
}
}
function LazyMan(name) {
return new LazyManClass(name)
}
8、某公司 1 到 12 月份的销售额存在一个对象里面
如下:{1:222, 2:123, 5:888},请把数据处理为如下结构:[222, 123, null, null, 888, null, null, null, null, null, null, null]。
let obj = {1:222, 2:123, 5:888};
const result = Array.from({ length: 12 }).map((_, index) => obj[index + 1] || null);
console.log(result)
9、实现 (5).add(3).minus(2) 功能
例: 5 + 3 - 2,结果为 6
Number.prototype.add = function(n) {
return this.valueOf() + n;
};
Number.prototype.minus = function(n) {
return this.valueOf() - n;
};
10、使用 sort() 对数组 [3, 15, 8, 29, 102, 22] 进 行排序,输出结果
输出:[102, 15, 22, 29, 3, 8]
解析:根据 MDN 上对 Array.sort()的解释,
默认的排序方法会将数组元素转换 为字符串,
然后比较字符串中字符的 UTF-16 编码顺序来进行排序。
所以'102' 会 排在 '15' 前面。
11、实现一个 sleep 函数
比如 sleep(1000) 意味着等待 1000 毫秒,可从 Promise、Generator、Async/Await 等角度实现
const sleep = (time) => {
return new Promise(resolve =>
setTimeout(resolve, time))
}
sleep(1000).then(() => { // 这里写你的骚操作})
12、下面代码中 a 在什么情况下会打印 1?
var a = ?;
if(a == 1 && a == 2 && a == 3){ console.log(1); }
//对象
var a = {
i: 1,
toString() {
return a.i++;
}
}
if( a == 1 && a == 2 && a == 3 ) {
console.log(1);
}
//数组
let a = [1,2,3];
a.toString = a.shift;
if( a == 1 && a == 2 && a == 3 ) {
console.log(1);
}
13、下面的代码打印什么内容,为什么?
var b = 10;
(function b(){
b = 20;
console.log(b);
})();
//ƒ b(){b = 20; console.log(b); }
// 首先函数声明比变量要高,其次 b = 20 没有 var 获取其他,
// 说明是 window 最 外层定义的变量。 js 作用域中,先找最近的
// 那就是 b fn ,直接打印了,如果 b = 20 有 var
// 那就 是打印 20
//立即执行函数不能修改函数名
14、两个数组合并成一个数组
请把两个数组 [‘A1’, ‘A2’, ‘B1’, ‘B2’, ‘C1’, ‘C2’, ‘D1’, ‘D2’] 和 [‘A’, ‘B’, ‘C’, ‘D’],合并 为 [‘A1’, ‘A2’, ‘A’, ‘B1’, ‘B2’, ‘B’, ‘C1’, ‘C2’, ‘C’, ‘D1’, ‘D2’, ‘D’]。
function concatArr (arr1, arr2) {
const arr = [...arr1];
let currIndex = 0;
for (let i = 0; i < arr2.length; i++) {
const RE = new RegExp(arr2[i])
while(currIndex < arr.length) {
++currIndex
if (!RE.test(arr[currIndex])) {
arr.splice(currIndex, 0, a2[i])
break;
}
}
}
return arr
}
var a1 = ['A1', 'A2', 'B1', 'B2', 'C1', 'C2', 'D1', 'D2'] var a2 = ['A', 'B', 'C', 'D']
const arr = concatArr(a1, a2)
console.log(a1)
// ['A1', 'A2', 'B1', 'B2', 'C1', 'C2', 'D1', 'D2'] console.log(a2) // ['A', 'B', 'C', 'D'] console.log(arr) // ['A1', 'A2', 'A', B1', 'B2', 'B', C1', 'C2', 'C', D1', 'D2', 'D']
15、使用 JavaScript Proxy 实现简单的数据绑定
<div id="app">
<input type="text" id="input">
<div> TODO: <span id="text"></span> </div>
</div>
const input = document.getElementById('input')
const text = document.getElementById('text')
const inputObj = new Proxy({}, {
get (target, key, receiver) {
return Reflect.get(target, key, receiver)
},
set (target, key, value, receiver) {
if (key === 'text') {
input.value = value text.innerHTML = value
}
return Reflect.set(target, key, value, receiver)
}
})
input.addEventListener('keyup', e => {
inputObj.text = e.target.value
})
//输入框输入值span标签值也会自动变
- 对象的键名只能是字符串和 Symbol 类型。
- 其他类型的键名会被转换成字符串类型。
- 对象转字符串默认会调用 toString 方法。
16、「移动零」给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非 零元素的相对顺序。
示例: 输入: [0,1,0,3,12] 输出: [1,3,12,0,0] 复制代码说明: 必须在原数组上操作,不能拷贝额外的数组。 尽量减少操作次 数
function zeroMove(array) {
let len = array.length;
let j = 0;
for(let i=0;i<len-j;i++){
if(array[i]===0){
array.push(0);
array.splice(i,1);
i --;
j ++;
}
}
return array;
}
17、请实现一个 add 函数,满足以下功能
add(1); // 1
add(1)(2); // 3
add(1)(2)(3); // 6
add(1)(2, 3); // 6
add(1, 2)(3); // 6
add(1, 2, 3); // 6
function currying(fn, length) {
length = length || fn.length; // 注释 1
return function (...args) { // 注释 2
return args.length >= length ? fn.apply(this, args) : currying(fn.bind(this, ...args), length - args.length) // 注释3、4、5
}
}
//其中注释部分 注释 1:第一次调用获取函数 fn 参数的长度,后续调用获取 fn 剩余参数的 长度
//注释 2:currying 包裹之后返回一个新函数,接收参数为 ...args
//注释 3:新函数接收的参数长度是否大于等于 fn 剩余参数需要接收的长度 //注释 4:满足要求,执行 fn 函数,传入新函数的参数
//注释 5:不满足要求,递归 currying 函数,新的 fn 为 bind 返回的新函数(bind 绑定了 ...args 参数,未执行),新的 length 为 fn 剩余参数的长度
18、算法题之「两数之和」
给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
示例: 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返 回 [0, 1]
function anwser (arr, target) {
let map = {}
for (let i = 0; i < arr.length; i++) {
map[arr[i]] = i
}
for (let i = 0; i < arr.length; i++) {
var d = target - arr[i]
if (map[d]) {
return [i, map[d]]
}
}
return new Error('404 not found')
}
19、在输入框中如何判断输入的是一个正确的网址。
function isUrl(url) {
const a = document.createElement("a");
a.href = url;
return ( [
/^(http|https):$/.test(a.protocol),
a.host,
a.pathname !== url,
a.pathname !== `/${url}`
].find(x => !x) === undefined
);
}
20、编程算法
用 JavaScript 写一个函数,输入 int 型,返回整数逆序后的字符串。如:输入 整型 1234,返回字符串“4321”。要求必须使用递归函数调用,不能用全局变量, 输入函数必须只有一个参数传入,必须返回字符串。
function fun(num) {
let num1 = num / 10;
let num2 = num % 10;
if (num1 < 1) {
return num;
} else {
num1 = Math.floor(num1);
return `${num2}${fun(num1)}`;
}
}
var a = fun(12345);
console.log(a);
console.log(typeof a);
本文涵盖了多个JavaScript编程挑战,包括找到对称数、数组旋转、字符串匹配、大小写翻转、数组操作、求交集、模拟类行为、处理销售数据、实现数学运算、睡眠函数、条件判断、代码解析、数组合并、数据绑定、移动零、函数柯里化、两数之和检查网址正确性等。通过这些挑战,深入理解JavaScript的核心特性和实际应用。
1342

被折叠的 条评论
为什么被折叠?



