We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
输出数组中所有两个的数相加等于7的两个数
要求:以数组的形式返回
例如:
给一个数组如下:
let arr = [8, 4, 2, 5, 1, 3, 6, 9]
输出两个数之和为7的两个数:
[[4, 3], [2, 5], [1, 6]]
遍历数组,利用indexOf方法查找,数组中有没有其他数与当前的数相加等7的值
以上面例子为例,要注意的一个点:
要避免重复查找,比如我们遍历到4时,可以找到目标数3, 但当我们遍历到3时,应当注意从3往后找目标数,而非从数组的起始位置查找
indexOf 方法有两个参数:
let targetArr = (arr, target) => { let newArr = [] arr.forEach((item, index) => { let num = target - item let i = arr.indexOf(num, index) if (i > -1) { newArr.push([item, arr[i]]) } }) return newArr } let arr = [8, 4, 2, 5, 1, 3, 6, 9] targetArr(arr, 7) // 调用
The text was updated successfully, but these errors were encountered:
No branches or pull requests
题目
输出数组中所有两个的数相加等于7的两个数
要求:以数组的形式返回
例如:
给一个数组如下:
输出两个数之和为7的两个数:
解析
遍历数组,利用indexOf方法查找,数组中有没有其他数与当前的数相加等7的值
以上面例子为例,要注意的一个点:
要避免重复查找,比如我们遍历到4时,可以找到目标数3, 但当我们遍历到3时,应当注意从3往后找目标数,而非从数组的起始位置查找
indexOf 方法有两个参数:
答案
The text was updated successfully, but these errors were encountered: