首页 > 解决方案 > 如何最小化这些 if 语句?

问题描述

阿拉伯字母具有分配给它们的数字。我正在尝试计算给定单词的数量,如下所示。添加每个字母的数字以计算单词的数字。我正在通过 if 语句检查单词的每个字母,即,如果单词中的字母等于给定的字母,它会将其值推送到数组中。最后,我将数组的所有值相加以给出整个单词的数字。

var x = 'افتخار';

y = [];


for (let i = 0; i < x.length; i++) {

    if (x[i] == ' ') {
        y.push(0);
    }
    if (x[i] == 'ا' || x[i] == 'آ' || x[i] == 'ء') {
        y.push(1);
    }
    if (x[i] == 'ب' || x[i] == 'پ') {
        y.push(2);
    }
    if (x[i] == 'ج' || x[i] == 'چ') {
        y.push(3);
    }
    if (x[i] == 'د' || x[i] == 'ڈ') {
        y.push(4);
    }
    if (x[i] == 'ه' || x[i] == 'ھ') {
        y.push(5);
    }
    if (x[i] == 'و') {
        y.push(6);
    }
    if (x[i] == 'ز' || x[i] == 'ژ') {
        y.push(7);
    }
    if (x[i] == 'ح') {
        y.push(8);
    }
    if (x[i] == 'ط') {
        y.push(9);
    }
    if (x[i] == 'ی') {
        y.push(10);
    }
    if (x[i] == 'ک') {
        y.push(20);
    }
    if (x[i] == 'ل') {
        y.push(30);
    }
    if (x[i] == 'م') {
        y.push(40);
    }
    if (x[i] == 'ن') {
        y.push(50);
    }
    if (x[i] == 'س') {
        y.push(60);
    }
    if (x[i] == 'ع') {
        y.push(70);
    }
    if (x[i] == 'ف') {
        y.push(80);
    }
    if (x[i] == 'ص') {
        y.push(90);
    }
    if (x[i] == 'ق') {
        y.push(100);
    }
    if (x[i] == 'ر') {
        y.push(200);
    }
    if (x[i] == 'ش') {
        y.push(300);
    }
    if (x[i] == 'ت' || x[i] == 'ٹ') {
        y.push(400);
    }
    if (x[i] == 'ث') {
        y.push(500);
    }
    if (x[i] == 'خ') {
        y.push(600);
    }
    if (x[i] == 'ذ') {
        y.push(700);
    }
    if (x[i] == 'ض') {
        y.push(800);
    }
    if (x[i] == 'ظ') {
        y.push(900);
    }
    if (x[i] == 'غ') {
        y.push(1000);
    }
}
console.log(y.reduce((a, b) => a + b, 0));

有没有更好的方法来编写这个以最小化使用的 if 语句的数量?

标签: javascriptarraysif-statement

解决方案


whatever = {
  " ": 0,
  "ا": Number(1), // I couldn't write 1 because some Arabic black magic block me
  ...,
}

for (let i = 0; i < x.length; i++) {
    if (x[i] in whatever) {
        y.push(x[i])
    }
}

推荐阅读