var arr=[1,2,3,4,5,6,7]; function fn(a){ console.log(a) } var narr=arr.map(function(item){ }) return "星期"+item console.log(narr) 这个代码哪里错误了
时间: 2024-02-10 08:25:27 浏览: 35
这段代码错误的地方在于`map`函数的回调函数中没有返回值。在回调函数中应该返回一个处理后的值,然后`map`函数会将每个元素都传递给回调函数进行处理,并返回一个新的数组。
修改后的代码如下:
```javascript
var arr = [1, 2, 3, 4, 5, 6, 7];
function fn(a) {
console.log(a)
}
var narr = arr.map(function(item) {
return "星期" + item;
});
console.log(narr);
```
这样就会输出`["星期1", "星期2", "星期3", "星期4", "星期5", "星期6", "星期7"]`。
相关问题
var arr = [1, 2, 3, 4]; function dealArr(array, fn) { return array } var newArr = dealArr(arr, function (item) { return item + 2; }); console.log(newArr); // [3,4,5,6] console.log(arr); // [1,2,3,4]哪里有问题
代码没有问题,只是缺少了对数组内元素的操作。
在 `dealArr` 函数内部,需要对传入的数组进行处理,才能得到预期结果。可以使用 `map` 方法对数组内每一项进行操作:
```
function dealArr(array, fn) {
return array.map(fn);
}
```
这样,当调用 `dealArr` 函数时,就能得到正确的结果:
```
var newArr = dealArr(arr, function (item) {
return item + 2;
});
console.log(newArr); // [3,4,5,6]
console.log(arr); // [1,2,3,4]
```
var arr = [] function fn(n) { if (n == 1) { return arr.push(n); }else { return arr.push(fn(n-1)) } } fn(100) console.log(arr)返回值为什么不是1-100
这是因为在代码中,`fn(n-1)` 的返回值是一个数组,而非数字。因此,每次调用 `fn()` 函数时,都会将一个包含数字的数组 `push` 到 `arr` 数组中,而不是单独的数字。因此,最后 `arr` 数组中的元素都是包含数字的数组,而非单独的数字。正确的代码应该是这样的:
```
var arr = []
function fn(n) {
if (n == 1) {
arr.push(n);
} else {
fn(n-1); // 递归调用
arr.push(n);
}
}
fn(100);
console.log(arr); // [1, 2, 3, ..., 100]
```
在这个代码中,我们将 `fn(n-1)` 的返回值改为了递归调用 `fn()` 函数,这样就可以将数字按照从小到大的顺序添加到 `arr` 数组中了。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)