每日一题:生成数组
发表于:2024-12-10
字数统计:1007 字
预计阅读4分钟
挑战介绍
本节我们来挑战一道大厂面试真题 —— 生成数组。
挑战准备
新建一个 createArr.js 文件,在文件里写一个名为 createArr 的函数,并导出这个函数,如下图所示:
这个文件在环境初始化时会自动生成,如果发现没有自动生成就按照上述图片自己创建文件和函数,函数代码如下:
js
function createArr(n) {
// 补充代码
}
module.exports = createArr;挑战内容
请封装一个函数,用来生成一个每项依次为 1 到 n 的数组。
不必考虑 n 过大的情况,本题中 0 <= n <= 10000。
示例:
js
输入:n = 1
输出:[1]
输入:n = 5
输出:[1,2,3,4,5]
输入:n = 10
输出:[1,2,3,4,5,6,7,8,9,10]
输入:n = 10000
输出:[1,2,3,4,5,6,7,8,9,10,...,9998,9999,10000]注意事项
- 文件名、函数名不可随意更改。
- 文件中编写的函数需要导出,否则将无法提交通过。
题解
第一种不解释了,第二种:Array.form方法接受两个参数,第一个参数是一个伪数组,所谓伪数组是能访问.length关键字的但不能调用数组上的方法的(因为数组实际上是一个特殊的对象,能够使用.length关键字)
js
function createArr(n) {
const result = []
for(let i = 1; i <= n; i++) {
result.push(i)
}
return result
}
function createArr2(n) {
const result = Array.from({ length: n}, (item, i) => item = i + 1)
return result
}附录
蓝桥
1.什么是伪数组
伪数组,也叫类数组,英文名称
Array-like,顾名思义,就是像数组但不是数组,有以下特征:
- 具有 length 属性。
- 可通过索引访问伪数组里的元素。
- 不能调用数组上的方法。
举个例子,函数的隐式参数
arguments就是一个伪数组,示例代码如下:jsfunction add() { console.log("arguments :>> ", arguments); console.log("arguments.length :>> ", arguments.length); console.log("arguments[0] :>> ", arguments[0]); arguments.push(1); } add(1, 2, 3);
2.JS 常见伪数组有哪些
有
arguments和DOM元素集合,示例代码如下:jsfunction add() { console.log("arguments :>> ", arguments); } add(1, 2, 3); const DOMTags = document.getElementsByClassName("test"); console.log("DOMTags :>> ", DOMTags); console.log("document.childNodes :>> ", document.childNodes);
3.伪数组的类型是什么
调用
Object.prototype.toString方法来看一下伪数组的类型,示例代码如下:jsfunction add() { console.log( "typeof arguments :>> ", Object.prototype.toString.call(arguments) ); } add(1, 2, 3); const DOMTags = document.getElementsByClassName("test"); console.log("typeof DOMTags", Object.prototype.toString.call(DOMTags)); console.log( "typeof document.childNodes :>> ", Object.prototype.toString.call(document.childNodes) );
可以看到,伪数组的类型是专门的引用类型,比如 Arguments 对象、HTMLCollection、NodeList。
4.伪数组如何转数组
可以使用
Array.from、扩展运算符和Array.prototype.slice方法来实现伪数组转数组。Array.from
jsfunction add() { const args = Array.from(arguments); args.push(1); // 可以使用数组上的方法了 console.log(Object.prototype.toString.call(args)); // '[object Array]' } add(1, 2, 3);扩展运算符
jsfunction add() { const args = [...arguments]; args.push(1); // 可以使用数组上的方法了 console.log(Object.prototype.toString.call(args)); // '[object Array]' } add(1, 2, 3);数组 slice 方法
这个方法现在不常用了,但 ES6 之前没有扩展运算符和
Array.from,用的就是这个方法。jsfunction add() { const args = Array.prototype.slice.call(arguments); // 也可以这么写 const args = [].slice.call(arguments) args.push(1); // 可以使用数组上的方法了 console.log(Object.prototype.toString.call(args)); // '[object Array]' } add(1, 2, 3);
Array.prototype.slice方法要调用call的原因和Object.prototype.toString要调用call的原因一样,在之前的章节“实现类型判断里”讲过。
