javascript - 如何最小化这些 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 语句的数量?
解决方案
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])
}
}
推荐阅读
- python - .png 图像中的空白背景转换为黑色、白色和其他颜色
- angular - Angular 6 - html 中的秒数
- ghost-blog - 在作者循环中获取最新帖子
- ios - MapView 委托返回 nil
- xml - 如何修复 Shopware 图像导入错误 - 需要订单号和图像
- javafx - 通过单击或悬停等获取 GridPane 对象中的单元格位置。javafx
- go - 是否有自动检测 pubsub 的新分片的 golang redis 客户端?
- reactjs - 在构造函数中声明从未使用过的 React 道具的正确方法
- javascript - 没被选中的字段怎么取?
- reactjs - 在另一个展示组件中包含一个展示组件是一种反模式吗?