【问题标题】:A function that joins two arrays JS连接两个数组JS的函数
【发布时间】:2022-11-02 18:40:29
【问题描述】:

我需要编写一个函数 combineArray(arr1, arr2),它接受 2 个数组,并返回一个仅由数组 arr1 和 arr2 的数字元素组成的新数组。 例如:

 combineArray([12, "User01", 22, true, -8], ["Index", 6, null, 15]));  result --> [12, 22, -8, 6, 15]

我试着这样做:

function combineArray(arr1, arr2) {
    let numArr = [];
    let newArr = arr1.concat(arr2);
    for(let i = 0; i < newArr.lenght; i++){
        if(typeof newArr[i] == "number") numArr.push(newArr[i]);
    }
    return numArr
}

let result = combineArray([12, "User01", 22, true, -8], ["Index", 6, null, 15])
console.log(result)

但我的函数返回空列表。

【问题讨论】:

  • newArr.length 不是 newArr.lenght
  • 错字:newArr.lenght => newArr.length

标签: javascript arrays function


【解决方案1】:

这是一个让我们所有人都犯错的错字……您在for 循环中输入了lenght 而不是length

尝试这个:

function combineArray(arr1, arr2) {
    let numArr = [];
    let newArr = arr1.concat(arr2);
    for(let i = 0; i < newArr.length; i++){
        if(typeof newArr[i] == "number") numArr.push(newArr[i]);
    }
    return numArr
}

let result = combineArray([12, "User01", 22, true, -8], ["Index", 6, null, 15])
console.log(result)

【讨论】:

  • 错字问题需要关闭和删除,因为它们对网站没有未来价值。请不要回答他们。
  • @adiga 很公平,下次注意
  • OP 无法删除带有赞成答案的问题。请删除答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-09
相关资源
最近更新 更多