如何在Javascript中使用字符串模板执行添加操作

时间:2018-04-16 17:37:23

标签: javascript arrays ecmascript-6

1.Sample输入:

let arr = [1,3];
console.log(`Addition is ${arr[0]? arr[0]: 0} + ${arr[1] ? arr[1] : 0}`);

2.Sample输入:

let arr = [{card:0, cash:0},{card:1, cash: 2}];
 for(let i = 0; i < arr.length; i++){
     console.log(`No. of payments ${(arr[i].card || 0)} + ${(arr[i].cash ||  0)}`);
}

3 个答案:

答案 0 :(得分:4)

也许这就是你要找的......

&#13;
&#13;
let arr = [1,3];
console.log(`Adittion is ${arr[0]? arr[0]: 0} + ${arr[1] ? arr[1] : 0}`);

// or 

console.log(`Addition is ${(arr[0]? arr[0]: 0) + (arr[1] ? arr[1] : 0)}`);

// If the socond one is the one you wanted, you can do it using reduce instead summing all positions

console.log(`Addition is ${arr.reduce((a,b)=>a+b)}`);
&#13;
&#13;
&#13;

<强>更新 这是你的第二个样本。这是完全不同的,因为在这里你没有使用数组,你使用的是一个对象数组,实现方式也不一样。

PD:考虑问一个新问题什么时候与你之前提出的问题不同

&#13;
&#13;
//In Your second sample you are using an array of objects, not an array of numbers so the implementation is different

let arr = [{card:0, cash:0},{card:1, cash: 2}];

arr.map(a=>{console.log(`No. of payments ${a.card + a.cash}`)})

//If you only want the total it would be

console.log(`No. of payments ${arr.map(a=>a.card + a.cash).reduce((a,b)=>a+b)}`)
&#13;
&#13;
&#13;

答案 1 :(得分:1)

要使其正常工作,您需要将两个操作数放在同一个括号中

`${(arr[0] || 0) + (arr[1] || 0)}`

我还使用||操作数选择器操作符逻辑或)来获得相同的结果(我认为它更具可读性)

答案 2 :(得分:0)

实现这一目标的方法:

&#13;
&#13;
let arr = [1,3];

// Method 1
console.log('Addition is ', (arr[0] ? arr[0]: 0) + (arr[1] ? arr[1] : 0));

// Method 2
console.log(`Addition is ${(arr[0]? arr[0]: 0) + (arr[1] ? arr[1] : 0)}`);

// Method 3
var sum = [1,3].reduce((a, b) => a + b, 0);
console.log('Addition is ', sum);

// Method 4
function addition(...elements) {
    let total = 0;
    for (const elem of elements) {
        total += elem;
    }
    return total;
}

console.log('Addition is ', addition(...arr));
&#13;
&#13;
&#13;