我想知道如何組合具有相同字串值但不同數字的兩個(或更多)變數。
例如,如果您要組合存在于兩個不同食譜中的成分串列。對于購物清單,例如:
let ingredient1 = 1 " apple";
let ingredient2 = 2 " apple";
//combining ingredient1 and ingredient 2 would produce something like totalIngredients = 3 apples;
我可以弄清楚復數形式,但我無法弄清楚如何組合這兩個字串,并且僅在它們匹配時才增加數字。
uj5u.com熱心網友回復:
就像其他人所指出的那樣,您應該將您的原料作為物品存放。實作此目的的一種方法是擁有一個存盤計數和成分型別的類。然后,您可以定義一個函式來檢查給定型別并回傳成分計數。
class Ingredient {
constructor(count, type) {
this.count = count;
this.type = type;
}
};
const countByType = (type) => ingredients.reduce((sum, ingredient) => {
if (ingredient.type === type) {
return sum = ingredient.count;
}
return sum;
}, 0);
const ingredients = [];
ingredients.push(new Ingredient(1, "apple"));
ingredients.push(new Ingredient(2, "apple"));
ingredients.push(new Ingredient(5, "orange"));
console.log(`${countByType("apple")} apples`);
console.log(`${countByType("orange")} oranges`);
如果您愿意,也可以在沒有類的情況下實作相同的效果:
const countByType = (type) => ingredients.reduce((sum, ingredient) => {
if (ingredient.type === type) {
return sum = ingredient.count;
}
return sum;
}, 0);
const ingredients = [];
ingredients.push({count: 1, type: "apple"});
ingredients.push({count: 2, type: "apple"});
ingredients.push({count: 5, type: "orange"});
console.log(`${countByType("apple")} apples`);
console.log(`${countByType("orange")} oranges`);
uj5u.com熱心網友回復:
如果我是你或 obj ,請制作一個 json,像這樣
const r = {
{
Item: “Apple”,
Amount: 1
},
{
Item: “Apple”,
Amount: 1
}
}
然后取數量并把它們放在一起,以及配料匹配
uj5u.com熱心網友回復:
你不能結合這兩種成分,它應該進行計算,因為let ingredient1 = 1 " apple";會產生一個字串 1 apple
你可以這樣做:
let ingredient = 'apple'
let ingredient1 = 1
let ingredient2 = 2
let totalIngredients = ingredient1 ingredient2 ingredient
或者可能使用for回圈遍歷所有成分并將其添加到總數中,然后添加'apple'
uj5u.com熱心網友回復:
如何對作為變數子字串的數字求和?
通過將子字串轉換為數字。如果數字位于字串的開頭,您可以使用parseInt.
parseInt(ingredient1) parseInt(ingredient2)
要檢查型別,您可以使用例如
let ingredient1 = 1 " apple";
let ingredient2 = 2 " apple";
let type1 = ingredient1.slice(ingredient1.indexOf(' ') 1);
let type2 = ingredient2.slice(ingredient2.indexOf(' ') 1);
if (type1 === type2) {
console.log(`${parseInt(ingredient1) parseInt(ingredient2)} ${type1}`);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/354223.html
標籤:javascript 变量
上一篇:自動將變數名稱傳遞給串列
下一篇:php加號保持零作為第一個字符
