Javascript forEach 用函数修改数值数组
Javascript forEach to modify numeric arrays with a function
我正在尝试对两个数组中的每组数字执行计算
var close_px = [];
close_px.push([9,9.5,10.2,10.3,10.6]);
close_px.push([5,5.7,5.3,5.1,5,6]);
close_px.forEach(element => element / element[0]-1);
我试图输出的是每个数组计算为偏离初始数字的百分比。
对于第一个数组,它将是:
1: 9 /9 -1
2: 9.5/9 - 1
3: 10.2/9 - 1
4: 10.3/9 - 1
5: 10.6/9 - 1
不确定我是否明白这一点,但这可能是您需要的:
const close_px = [];
close_px.push([9,9.5,10.2,10.3,10.6]);
close_px.push([5,5.7,5.3,5.1,5,6]);
const result = close_px.map(array => array.map(element => element / array[0] - 1));
console.log(JSON.stringify(result, null, 2));
我正在尝试对两个数组中的每组数字执行计算
var close_px = [];
close_px.push([9,9.5,10.2,10.3,10.6]);
close_px.push([5,5.7,5.3,5.1,5,6]);
close_px.forEach(element => element / element[0]-1);
我试图输出的是每个数组计算为偏离初始数字的百分比。
对于第一个数组,它将是:
1: 9 /9 -1
2: 9.5/9 - 1
3: 10.2/9 - 1
4: 10.3/9 - 1
5: 10.6/9 - 1
不确定我是否明白这一点,但这可能是您需要的:
const close_px = [];
close_px.push([9,9.5,10.2,10.3,10.6]);
close_px.push([5,5.7,5.3,5.1,5,6]);
const result = close_px.map(array => array.map(element => element / array[0] - 1));
console.log(JSON.stringify(result, null, 2));