我想在 Javascript 中轉換數學運算。例如,給定一個“-”,它應該被轉換為“ ”、“*”-“/”等等。
我當前的代碼是一個開關盒,執行起來真的很慢:
if (contents.className == "buttonfunction") {
if (invert == true) {
switch (contents.innerHTML) {
case " ":
contents.innerHTML = "-";
break;
case "-":
contents.innerHTML = " ";
break;
case "*":
contents.innerHTML = "/";
break;
case "/":
contents.innerHTML = "*";
break;
}
}
document.body.appendChild(contents);
}
這個問題有更好/更快的解決方案嗎?
uj5u.com熱心網友回復:
性能可以忽略不計,但對于將一個事物映射到另一個事物的操作,從長遠來看,表驅動的方法通常更易于維護:
const inverseOperations = {
' ': '-',
'-': ' ',
'/': '*',
'*': '/',
};
if (contents.className == "buttonfunction") {
const operation = contents.innerHTML
if (invert == true && inverseOperations[operation]) {
contents.innerHTML = inverseOperations[operation];
}
document.body.appendChild(contents);
}
uj5u.com熱心網友回復:
我添加了一些背景關系來制作一個運行示例。
順便說一句,這里使用的方法是反轉規則的映射,替換了您在 switch 陳述句中使用的邏輯:
let invert = true;
//granular map of pairs declaring the inverse of each operator
//it could be declared inline here but it could be also fed with the addInversionInMap
let inverted = {}; //{ ' ' : '-', '-' : ' ', '*' : '/', '/' : '*'}
addInversionInMap(' ','-');
addInversionInMap('*','/');
//feeds the inverted map without repeating the both the sides in declaration
function addInversionInMap(op, opInverted){
inverted[op] = opInverted;
inverted[opInverted] = op;
}
//on document ready adds the click handler to every .buttonfunction elements
document.addEventListener("DOMContentLoaded", function() {
addClickHandlerToButtonsFunction();
});
//adds the handler for click event on .buttonfunction
function addClickHandlerToButtonsFunction(){
let btns = Object.values(document.getElementsByClassName('buttonfunction'));
for(let btn of btns){
btn.addEventListener('click', invertValue);
}
}
//return the inverted operator based on the inverted map
//(or return the operator as is if there's no way to invert)
function getInvert(operator){
if(inverted.hasOwnProperty(operator))
return inverted[operator];
else
return operator;
}
//inverts the value of the element whose id is declared in the data-target attribvute
//of the button that triggered the click event (such element should be input type text)
function invertValue(){
let contents = window.event.target;
if (contents.className == "buttonfunction") {
if (invert == true) {
let targetId = contents.getAttribute('data-target');
let target = document.getElementById(targetId);
//I'm using value so I expect the element to be input type text
target.value = getInvert(target.value);
}
}
}
button.buttonfunction{
cursor: pointer;
}
<input id="input" type="text"></input>
<button type="button" class="buttonfunction" data-target="input">Invert</button>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/464582.html
標籤:javascript 功能 数学
上一篇:清除回聲歷史
