构造一个相对于 JavaScript 中第一个数组元素的加法/减法数组
问题
我们需要编写一个JavaScript函数,它接受一个正整数数组。我们的函数应该将此数组映射到字符串整数数组。
数组应该包含我们应该添加/减去第一个元素以获得相应元素的数字。
例如
[4, 3, 6, 2]
应该返回-
['+0', '-1', '+2', '-2']
示例
以下是代码-
const arr = [4, 3, 6, 2];
const buildRelative = (arr = []) => {
const res = [];
let num = '';
for(let i of arr){
if(i - arr[0] >= 0){
num += '+' + (i - arr[0])
}else{
num += i - arr[0]
};
res.push(num);
num = '';
};
return res;
};
console.log(buildRelative(arr));输出结果[ '+0', '-1', '+2', '-2' ]
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短