每日一题:生成数组
每日一题:生成数组
挑战介绍
本节我们来挑战一道大厂面试真题 —— 生成数组。
挑战准备
新建一个 createArr.js 文件,在文件里写一个名为 createArr 的函数,并导出这个函数,如下图所示:
这个文件在环境初始化时会自动生成,如果发现没有自动生成就按照上述图片自己创建文件和函数,函数代码如下:
1 | function createArr(n) { |
挑战内容
请封装一个函数,用来生成一个每项依次为 1 到 n 的数组。
不必考虑 n 过大的情况,本题中 0 <= n <= 10000。
示例:
1 | 输入:n = 1 |
注意事项
- 文件名、函数名不可随意更改。
- 文件中编写的函数需要导出,否则将无法提交通过。
题解
第一种不解释了,第二种:Array.form方法接受两个参数,第一个参数是一个伪数组,所谓伪数组是能访问.length关键字的但不能调用数组上的方法的(因为数组实际上是一个特殊的对象,能够使用.length关键字)
1 | function createArr(n) { |
附录
蓝桥
1.什么是伪数组
伪数组,也叫类数组,英文名称
Array-like,顾名思义,就是像数组但不是数组,有以下特征:
- 具有 length 属性。
- 可通过索引访问伪数组里的元素。
- 不能调用数组上的方法。
举个例子,函数的隐式参数
arguments就是一个伪数组,示例代码如下:
1
2
3
4
5
6
7
8 function 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元素集合,示例代码如下:
1
2
3
4
5
6
7
8
9 function 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方法来看一下伪数组的类型,示例代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 function 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
1
2
3
4
5
6
7 function add() {
const args = Array.from(arguments);
args.push(1); // 可以使用数组上的方法了
console.log(Object.prototype.toString.call(args)); // '[object Array]'
}
add(1, 2, 3);扩展运算符
1
2
3
4
5
6
7 function add() {
const args = [...arguments];
args.push(1); // 可以使用数组上的方法了
console.log(Object.prototype.toString.call(args)); // '[object Array]'
}
add(1, 2, 3);数组 slice 方法
这个方法现在不常用了,但 ES6 之前没有扩展运算符和
Array.from,用的就是这个方法。
1
2
3
4
5
6
7
8 function 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的原因一样,在之前的章节“实现类型判断里”讲过。
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 江月迟迟!
