给定一个数组A[0,1,...,n-1],请构建一个数组B[0,1,...,n-1],其中B中的元素B[i]=A[0]A[1]...*A[i-1]A[i+1]...*A[n-1]。不能使用除法。(注意:规定B[0] = A[1] * A[2] * ... * A[n-1],B[n-1] = A[0] * A[1] * ... * A[n-2];) 对于A长度为1的情况,B无意义,故而无法构建,因此该情况不会存在。
解答:
function multiply(array)
{
var result = []
for(let i = 0;i<array.length;i++){
let temp = array.filter((cueVal,index)=> i!==index)
let t = 1;
temp.map(val=>t=t*val);
result.push(t)
}
return result
}
filter
filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。
注意: filter() 不会对空数组进行检测。
注意: filter() 不会改变原始数组。
注意:返回值是一个数组,包含了符合条件的所有元素。如果没有符合条件的元素则返回空数组。
语法
array.filter(function(currentValue,index,arr), thisValue)
// currentValue 必须。当前元素的值
// index 可选。当前元素的索引值
// arr 可选。当前元素属于的数组对象
// thisValue 可选。对象作为该执行回调时使用,传递给函数,用作 "this" 的值。如果省略了 thisValue ,"this" 的值为 "undefined"
不过需要注意:
// 普通函数
let arr = [1,2,3,4]
arr.filter(function(a,b,c){
console.log(a,b,c);
console.log(this)
},300)
/*
1 0 [ 1, 2, 3, 4 ]
[Number: 300]
2 1 [ 1, 2, 3, 4 ]
[Number: 300]
3 2 [ 1, 2, 3, 4 ]
[Number: 300]
4 3 [ 1, 2, 3, 4 ]
[Number: 300]
*/
// 箭头函数
let arr = [1,2,3,4]
arr.filter((a,b,c)=>{
console.log(a,b,c);
console.log(this)
},300)
/*
1 0 [ 1, 2, 3, 4 ]
{}
2 1 [ 1, 2, 3, 4 ]
{}
3 2 [ 1, 2, 3, 4 ]
{}
4 3 [ 1, 2, 3, 4 ]
{}
*/
原因是:箭头函数中的this和作用域链上父级相同。
map
map() 方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。
map() 方法按照原始数组元素顺序依次处理元素。
注意: map() 不会对空数组进行检测。
注意: map() 不会改变原始数组。
语法
array.map(function(currentValue,index,arr), thisValue)
// currentValue 必须。当前元素的值
// index 可选。当前元素的索引值
// arr 可选。当前元素属于的数组对象
// thisValue 可选。对象作为该执行回调时使用,传递给函数,用作 "this" 的值。如果省略了 thisValue ,或者传入 null、undefined,"this" 的值为 "undefined"